react: Bug: MessageChannel in Scheduler prevents Jest test from exiting
React version: any Scheduler version: any up to current (0.23.0)
Steps To Reproduce
- Create Jest unit test.
- Select JSDom as test environment so that runtime will not have
setImmediatefunction. - JSDom still does not implement
MessageChannelhttps://github.com/jsdom/jsdom/issues/2448. IfMessageChannelis required to test some important functionality, one can add an implementation from Node.js as recommended in comment https://github.com/jsdom/jsdom/issues/2448#issuecomment-536242756window.MessageChannel = require('node:worker_threads').MessageChannel; - Add Scheduler or React as a dependency and require it in the test or one of the files under test.
- Run test
Link to code example: https://github.com/victor-homyakov/scheduler-jest-jsdom-example
The current behavior
Test is endless. Jest won’t stop. Console shows a message
Jest did not exit one second after the test run has completed.
'This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.
Running Jest with --detectOpenHandles outputs:
Jest has detected the following 1 open handle potentially keeping Jest from exiting:
● MESSAGEPORT
> 1 | require('scheduler');
| ^
at node_modules/scheduler/cjs/scheduler.development.js:569:17
The expected behavior
Code at https://github.com/facebook/react/blob/5426af3d50ff706f3ebeb4764f838e0a3812bf9a/packages/scheduler/src/forks/Scheduler.js#L621 should unref the handle:
channel.port1.onmessage = performWorkUntilDeadline;
// Allow the thread to exit if this is the only active handle in the event system
if (channel.port1.unref) {
channel.port1.unref();
}
About this issue
- Original URL
- State: open
- Created 4 years ago
- Reactions: 2
- Comments: 15 (5 by maintainers)
Thank you very much for the workaround! In practice I found that simply
unrefing the port immediately on creation did not do the trick, because as soon asschedulercallschannel.port1.onmessage = performWorkUntilDeadlinethe port becomes reffed again. I had to do something more complex:Alternatively, as I happen to be using Mocha, I found that the
--exitflag also worked.The workaround is to use patched MessageChannel in JSDom, something like