Skip to content

Commit 5aeb882

Browse files
committed
fix(cleanup): microtask flushing now supports fake timers
1 parent 96c79f8 commit 5aeb882

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

src/flush-microtasks.js

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,23 @@
33
// and the part that is not cannot easily have useful tests written
44
// anyway. So we're just going to ignore coverage for this file
55
/**
6-
* copied from React's enqueueTask.js
6+
* copied and modified from React's enqueueTask.js
77
*/
88

9+
// the jest fake timers bit is borrowed from DOM Testing Library
10+
// and is copy/pasted rather than imported because I'm not sure
11+
// we want to expose this functionality from DOM Testing Library
12+
// just yet (or ever)
13+
const globalObj = typeof window === 'undefined' ? global : window
14+
15+
function getIsUsingFakeTimers() {
16+
return (
17+
typeof jest !== 'undefined' &&
18+
(globalObj.setTimeout?.hasOwnProperty('_isMockFunction') ||
19+
globalObj.setTimeout?.hasOwnProperty('clock'))
20+
)
21+
}
22+
923
let didWarnAboutMessageChannel = false
1024
let enqueueTask
1125
try {
@@ -43,7 +57,15 @@ try {
4357
export default function flushMicroTasks() {
4458
return {
4559
then(resolve) {
46-
enqueueTask(resolve)
60+
if (getIsUsingFakeTimers()) {
61+
// without this, a test using fake timers would never get microtasks
62+
// actually flushed. I spent several days on this... Really hard to
63+
// reproduce the problem, so there's no test for it. But it works!
64+
jest.advanceTimersByTime(0)
65+
resolve()
66+
} else {
67+
enqueueTask(resolve)
68+
}
4769
},
4870
}
4971
}

0 commit comments

Comments
 (0)