Skip to content

Commit

Permalink
fix(cleanup): microtask flushing now supports fake timers
Browse files Browse the repository at this point in the history
  • Loading branch information
kentcdodds committed Jun 24, 2020
1 parent 96c79f8 commit 5aeb882
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions src/flush-microtasks.js
Expand Up @@ -3,9 +3,23 @@
// and the part that is not cannot easily have useful tests written
// anyway. So we're just going to ignore coverage for this file
/**
* copied from React's enqueueTask.js
* copied and modified from React's enqueueTask.js
*/

// the jest fake timers bit is borrowed from DOM Testing Library
// and is copy/pasted rather than imported because I'm not sure
// we want to expose this functionality from DOM Testing Library
// just yet (or ever)
const globalObj = typeof window === 'undefined' ? global : window

function getIsUsingFakeTimers() {
return (
typeof jest !== 'undefined' &&
(globalObj.setTimeout?.hasOwnProperty('_isMockFunction') ||
globalObj.setTimeout?.hasOwnProperty('clock'))
)
}

let didWarnAboutMessageChannel = false
let enqueueTask
try {
Expand Down Expand Up @@ -43,7 +57,15 @@ try {
export default function flushMicroTasks() {
return {
then(resolve) {
enqueueTask(resolve)
if (getIsUsingFakeTimers()) {
// without this, a test using fake timers would never get microtasks
// actually flushed. I spent several days on this... Really hard to
// reproduce the problem, so there's no test for it. But it works!
jest.advanceTimersByTime(0)
resolve()
} else {
enqueueTask(resolve)
}
},
}
}

0 comments on commit 5aeb882

Please sign in to comment.