Skip to content

Commit 6667cc2

Browse files
authored
feat: adds onTimeout option to waitFor (#885)
1 parent c42bae1 commit 6667cc2

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

src/__tests__/waitFor.test.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,32 @@ test.each([TimerMode.Legacy, TimerMode.Modern])(
115115
}
116116
);
117117

118+
test.each([TimerMode.Legacy, TimerMode.Modern])(
119+
'waits for assertion until timeout is met with %s fake timers',
120+
async (fakeTimerType) => {
121+
jest.useFakeTimers(fakeTimerType);
122+
123+
const mockErrorFn = jest.fn(() => {
124+
throw Error('test');
125+
});
126+
127+
const mockHandleFn = jest.fn((e) => e);
128+
129+
try {
130+
await waitFor(() => mockErrorFn(), {
131+
timeout: 400,
132+
interval: 200,
133+
onTimeout: mockHandleFn,
134+
});
135+
} catch (error) {
136+
// suppress
137+
}
138+
139+
expect(mockErrorFn).toHaveBeenCalledTimes(3);
140+
expect(mockHandleFn).toHaveBeenCalledTimes(1);
141+
}
142+
);
143+
118144
test.each([TimerMode.Legacy, TimerMode.Legacy])(
119145
'awaiting something that succeeds before timeout works with %s fake timers',
120146
async (fakeTimerType) => {

src/waitFor.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export type WaitForOptions = {
2929
timeout?: number,
3030
interval?: number,
3131
stackTraceError?: ErrorWithStack,
32+
onTimeout?: (error: Error) => Error,
3233
};
3334

3435
function waitForInternal<T>(
@@ -37,6 +38,7 @@ function waitForInternal<T>(
3738
timeout = DEFAULT_TIMEOUT,
3839
interval = DEFAULT_INTERVAL,
3940
stackTraceError,
41+
onTimeout,
4042
}: WaitForOptions
4143
): Promise<T> {
4244
if (typeof expectation !== 'function') {
@@ -179,6 +181,9 @@ function waitForInternal<T>(
179181
copyStackTrace(error, stackTraceError);
180182
}
181183
}
184+
if (typeof onTimeout === 'function') {
185+
onTimeout(error);
186+
}
182187
onDone(error, null);
183188
}
184189
});

typings/index.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,7 @@ type TextMatchOptions = {
388388
type WaitForOptions = {
389389
timeout?: number;
390390
interval?: number;
391+
onTimeout?: (error: Error) => Error;
391392
};
392393

393394
export type WaitForFunction = <T = any>(

0 commit comments

Comments
 (0)