Skip to content

Commit b0244d9

Browse files
fix: display stack trace and code frame for findBy error (#581)
Inspired by https://github.com/testing-library/dom-testing-library/blob/master/src/wait-for.js
1 parent 45ee867 commit b0244d9

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

src/helpers/errors.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,13 @@ export const createQueryByError = (error: Error, callsite: Function) => {
3939
throw new ErrorWithStack(error.message, callsite);
4040
};
4141

42+
export function copyStackTrace(target: Error, stackTraceSource: Error) {
43+
target.stack = stackTraceSource.stack.replace(
44+
stackTraceSource.message,
45+
target.message
46+
);
47+
}
48+
4249
const warned = {};
4350

4451
export function printDeprecationWarning(functionName: string) {

src/waitFor.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22

33
import * as React from 'react';
44
import act from './act';
5-
import { throwRemovedFunctionError } from './helpers/errors';
5+
import {
6+
ErrorWithStack,
7+
throwRemovedFunctionError,
8+
copyStackTrace,
9+
} from './helpers/errors';
610

711
const DEFAULT_TIMEOUT = 4500;
812
const DEFAULT_INTERVAL = 50;
@@ -26,10 +30,13 @@ function waitForInternal<T>(
2630
const timeout = options?.timeout ?? DEFAULT_TIMEOUT;
2731
const interval = options?.interval ?? DEFAULT_INTERVAL;
2832
const startTime = Date.now();
33+
// Being able to display a useful stack trace requires generating it before doing anything async
34+
const stackTraceError = new ErrorWithStack('STACK_TRACE_ERROR', waitFor);
2935

3036
return new Promise((resolve, reject) => {
3137
const rejectOrRerun = (error) => {
3238
if (Date.now() - startTime >= timeout) {
39+
copyStackTrace(error, stackTraceError);
3340
reject(error);
3441
return;
3542
}

0 commit comments

Comments
 (0)