Steps to reproduce the behavior:
git clone https://github.com/kentcdodds/jest-save-enter
cd jest-save-enter
npm install
npm run test
Then open the example.test.js and save it a few times until you notice the issue. The test passes, but every now and then, we'll get a console.error from React.
Here's the code in the example.test.js file:
const React = require('react')
const ReactDOM = require('react-dom')
const {act} = require('react-dom/test-utils')
function Comp() {
const [state, setState] = React.useState()
React.useEffect(() => {
setTimeout(() => {
console.log('updating state')
setState('blah')
})
}, [state])
return null
}
test('example', async () => {
const container = document.createElement('div')
// using `act` is required to get effect callbacks run when rendering components
// (React Testing Library does this automatically)
act(() => {
ReactDOM.render(React.createElement(Comp), container)
})
// the `cleanup` function from React Testing Library (which also happens automatically)
// flushes all the in-flight effects by waiting for the next tick of the event loop
// this is basically a simplified version of: https://github.com/facebook/react/blob/master/packages/shared/enqueueTask.js
await new Promise((resolve) => setImmediate(resolve))
// this is the last thing that happens in cleanup (to avoid memory leaks)
ReactDOM.unmountComponentAtNode(container)
}
And here's some output:
When it works

Without changing anything, sometimes this happens

I expect the output to be consistent.
https://github.com/kentcdodds/jest-save-enter
This issue is best explained in video form (5 minutes): https://youtu.be/hRxf6QUwkow
System:
OS: macOS 10.15.4
CPU: (16) x64 Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz
Binaries:
Node: 12.13.1 - ~/n/bin/node
Yarn: 1.21.1 - ~/.yarn/bin/yarn
npm: 6.14.5 - /usr/local/bin/npm
npmPackages:
jest: ^26.0.1 => 26.0.1
I honestly have no idea what's going on here, but I definitely observe this happening sometimes in less contrived examples.
Related issues:
Looks like it may have to do with the setTimeout, I was able to modify the test to make sure it's using fake timers when it's rendering to seemingly remove the randomness from it-- no idea if this is the best solution, but it's worked for me so far! haha https://github.com/kentcdodds/jest-save-enter/pull/1
Thanks, but changing the test is irrelevant. The fact jest is inconsistent with this is the bug in jest.
Most helpful comment
Thanks, but changing the test is irrelevant. The fact jest is inconsistent with this is the bug in jest.