File tree Expand file tree Collapse file tree 3 files changed +36
-5
lines changed
Expand file tree Collapse file tree 3 files changed +36
-5
lines changed Original file line number Diff line number Diff line change 1+ /* eslint-disable import/prefer-default-export */
2+ /* eslint-env jest */
3+ // Used to avoid using Jest's fake timers and Date.now mocks
4+ // See https://github.com/TheBrainFamily/wait-for-expect/issues/4 and
5+ // https://github.com/TheBrainFamily/wait-for-expect/issues/12 for more info
6+ const globalObj = typeof window === "undefined" ? global : window ;
7+
8+ // Currently this fn only supports jest timers, but it could support other test runners in the future.
9+ function runWithRealTimers ( callback : ( ) => any ) {
10+ const usingJestFakeTimers =
11+ // eslint-disable-next-line no-underscore-dangle
12+ ( globalObj . setTimeout as any ) . _isMockFunction &&
13+ typeof jest !== "undefined" ;
14+
15+ if ( usingJestFakeTimers ) {
16+ jest . useRealTimers ( ) ;
17+ }
18+
19+ const callbackReturnValue = callback ( ) ;
20+
21+ if ( usingJestFakeTimers ) {
22+ jest . useFakeTimers ( ) ;
23+ }
24+
25+ return callbackReturnValue ;
26+ }
27+
28+ export function getSetTimeoutFn ( ) {
29+ return runWithRealTimers ( ( ) => globalObj . setTimeout ) ;
30+ }
Original file line number Diff line number Diff line change 1+ import { getSetTimeoutFn } from "./helpers" ;
2+
13const defaults = {
24 timeout : 4500 ,
35 interval : 50
@@ -16,10 +18,7 @@ const waitForExpect = function waitForExpect(
1618 timeout = defaults . timeout ,
1719 interval = defaults . interval
1820) {
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 ;
21+ const setTimeout = getSetTimeoutFn ( ) ;
2322
2423 // eslint-disable-next-line no-param-reassign
2524 if ( interval < 1 ) interval = 1 ;
Original file line number Diff line number Diff line change @@ -12,7 +12,7 @@ beforeEach(() => {
1212 jest . useRealTimers ( ) ;
1313} ) ;
1414
15- test ( "it works with real timers even if they were set to fake before importing the module" , async ( ) => {
15+ test ( "it always uses real timers even if they were set to fake before importing the module" , async ( ) => {
1616 jest . useFakeTimers ( ) ;
1717 /* eslint-disable global-require */
1818 const importedWaitForExpect = require ( "./index" ) ;
@@ -27,6 +27,8 @@ test("it works with real timers even if they were set to fake before importing t
2727 numberToChange = 100 ;
2828 } , randomTimeout ) ;
2929
30+ jest . useFakeTimers ( ) ;
31+
3032 await importedWaitForExpect ( ( ) => {
3133 expect ( numberToChange ) . toEqual ( 100 ) ;
3234 } ) ;
You can’t perform that action at this time.
0 commit comments