Skip to content

manually flush microtasks in afterEach #514

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/flush-microtasks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/* istanbul ignore file */
// the part of this file that we need tested is definitely being run
// 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
*/

let didWarnAboutMessageChannel = false
let enqueueTask
try {
// read require off the module object to get around the bundlers.
// we don't want them to detect a require and bundle a Node polyfill.
const requireString = `require${Math.random()}`.slice(0, 7)
const nodeRequire = module && module[requireString]
// assuming we're in node, let's try to get node's
// version of setImmediate, bypassing fake timers if any.
enqueueTask = nodeRequire('timers').setImmediate
} catch (_err) {
// we're in a browser
// we can't use regular timers because they may still be faked
// so we try MessageChannel+postMessage instead
enqueueTask = callback => {
if (didWarnAboutMessageChannel === false) {
didWarnAboutMessageChannel = true
// eslint-disable-next-line no-console
console.error(
typeof MessageChannel !== 'undefined',
'This browser does not have a MessageChannel implementation, ' +
'so enqueuing tasks via await act(async () => ...) will fail. ' +
'Please file an issue at https://github.com/facebook/react/issues ' +
'if you encounter this warning.',
)
}
const channel = new MessageChannel()
channel.port1.onmessage = callback
channel.port2.postMessage(undefined)
}
}

export default function flushMicroTasks() {
return {
then(resolve) {
enqueueTask(resolve)
},
}
}
4 changes: 2 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {asyncAct} from './act-compat'
import flush from './flush-microtasks'
import {cleanup} from './pure'

// if we're running in a test runner that supports afterEach
Expand All @@ -8,7 +8,7 @@ import {cleanup} from './pure'
// or set the RTL_SKIP_AUTO_CLEANUP env variable to 'true'.
if (typeof afterEach === 'function' && !process.env.RTL_SKIP_AUTO_CLEANUP) {
afterEach(async () => {
await asyncAct(async () => {})
await flush()
cleanup()
})
}
Expand Down