Skip to content

Commit e9f383d

Browse files
author
pierrezimmermann
committed
refactor: rewrite test so that it is more explicit
1 parent f957246 commit e9f383d

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

src/__tests__/waitFor.test.tsx

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -204,21 +204,25 @@ test.each([false, true])(
204204
}
205205
);
206206

207-
const fibonaci = (n: number): number => {
208-
if (n === 0 || n === 1) {
209-
return 1;
207+
const blockThread = (timeToBlockThread: number, legacyFakeTimers: boolean) => {
208+
jest.useRealTimers();
209+
let end = Date.now() + timeToBlockThread;
210+
211+
while (Date.now() < end) {
212+
// do nothing
210213
}
211214

212-
return fibonaci(n - 1) + fibonaci(n - 2);
215+
jest.useFakeTimers({ legacyFakeTimers });
213216
};
214217

215-
test.each([false, true])(
218+
test.each([true, false])(
216219
'it should not depend on real time when using fake timers (legacyFakeTimers = %s)',
217-
async () => {
218-
jest.useFakeTimers({ legacyFakeTimers: false });
220+
async (legacyFakeTimers) => {
221+
jest.useFakeTimers({ legacyFakeTimers });
219222

220223
const mockErrorFn = jest.fn(() => {
221-
fibonaci(30);
224+
// Wait 10 seconds so that check time is longer than interval
225+
blockThread(10, legacyFakeTimers);
222226
throw new Error('test');
223227
});
224228

@@ -227,10 +231,13 @@ test.each([false, true])(
227231
timeout: 200,
228232
interval: 5,
229233
});
230-
} catch (error) {
231-
// suppress
234+
} catch (e) {
235+
// do nothing
232236
}
233237

238+
// Verify that even though time to perform check is longer than interval
239+
// test won't timeout until number of checks * interval >= timeout
240+
// ie fake timers have been advanced by timeout when waitfor rejects
234241
expect(mockErrorFn).toHaveBeenCalledTimes(41);
235242
}
236243
);

0 commit comments

Comments
 (0)