Skip to content

Commit a6f0b72

Browse files
brapifralgandecki
authored andcommitted
Get setTimeout lazily (#20)
* Get setTimeout and Date.now lazily This prevents from using old versions of setTimeout/Date.now * Modify withFakeTimers unit test to cover the correct scenario BREAKING CHANGE: If you combined fake timers with wait-for-expect that will most probably not work anymore. Please make an issue with your failing usecase, as we couldn't think of a situation where using wait-for-expect and fake timers in the same test would be necessary.
1 parent e1962de commit a6f0b72

File tree

2 files changed

+12
-8
lines changed

2 files changed

+12
-8
lines changed

src/index.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,3 @@
1-
// Used to avoid using Jest's fake timers and Date.now mocks
2-
// See https://github.com/TheBrainFamily/wait-for-expect/issues/4 and
3-
// https://github.com/TheBrainFamily/wait-for-expect/issues/12 for more info
4-
const { setTimeout } = typeof window !== "undefined" ? window : global;
5-
61
const defaults = {
72
timeout: 4500,
83
interval: 50
@@ -21,6 +16,11 @@ const waitForExpect = function waitForExpect(
2116
timeout = defaults.timeout,
2217
interval = defaults.interval
2318
) {
19+
// Used to avoid using Jest's fake timers and Date.now mocks
20+
// See https://github.com/TheBrainFamily/wait-for-expect/issues/4 and
21+
// https://github.com/TheBrainFamily/wait-for-expect/issues/12 for more info
22+
const { setTimeout } = typeof window !== "undefined" ? window : global;
23+
2424
// eslint-disable-next-line no-param-reassign
2525
if (interval < 1) interval = 1;
2626
const maxTries = Math.ceil(timeout / interval);

src/withFakeTimers.spec.ts

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,17 @@ import waitForExpect from "./index";
77
// line from the index.ts
88

99
beforeEach(() => {
10+
jest.resetModules();
1011
jest.restoreAllMocks();
1112
jest.useRealTimers();
1213
});
1314

14-
test("it works even if the timers are overwritten by jest", async () => {
15+
test("it works with real timers even if they were set to fake before importing the module", async () => {
1516
jest.useFakeTimers();
17+
/* eslint-disable global-require */
18+
const importedWaitForExpect = require("./index");
19+
jest.useRealTimers();
20+
1621
let numberToChange = 10;
1722
// we are using random timeout here to simulate a real-time example
1823
// of an async operation calling a callback at a non-deterministic time
@@ -22,8 +27,7 @@ test("it works even if the timers are overwritten by jest", async () => {
2227
numberToChange = 100;
2328
}, randomTimeout);
2429

25-
jest.runAllTimers();
26-
await waitForExpect(() => {
30+
await importedWaitForExpect(() => {
2731
expect(numberToChange).toEqual(100);
2832
});
2933
});

0 commit comments

Comments
 (0)