Skip to content

Commit 5814b29

Browse files
authored
fix(cleanup): microtask flushing now supports fake timers (#720)
1 parent 96c79f8 commit 5814b29

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

src/flush-microtasks.js

+19-2
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,18 @@
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+
function getIsUsingFakeTimers() {
10+
return (
11+
typeof jest !== 'undefined' &&
12+
typeof setTimeout !== 'undefined' &&
13+
(setTimeout.hasOwnProperty('_isMockFunction') ||
14+
setTimeout.hasOwnProperty('clock'))
15+
)
16+
}
17+
918
let didWarnAboutMessageChannel = false
1019
let enqueueTask
1120
try {
@@ -43,7 +52,15 @@ try {
4352
export default function flushMicroTasks() {
4453
return {
4554
then(resolve) {
46-
enqueueTask(resolve)
55+
if (getIsUsingFakeTimers()) {
56+
// without this, a test using fake timers would never get microtasks
57+
// actually flushed. I spent several days on this... Really hard to
58+
// reproduce the problem, so there's no test for it. But it works!
59+
jest.advanceTimersByTime(0)
60+
resolve()
61+
} else {
62+
enqueueTask(resolve)
63+
}
4764
},
4865
}
4966
}

0 commit comments

Comments
 (0)