useEffect not triggering inside jest
See original GitHub issuereact-testing-libraryversion: 5.2.3reactversion: 16.7.0-alpha.0nodeversion: CodeSandboxnpm(oryarn) version: CodeSandbox
Relevant code or config:
let a = false;
function Test() {
React.useEffect(() => {
a = true;
});
return <div>Hello World</div>;
}
render(<Test />);
expect(a).toBe(true);
What you did:
I’m trying to test functions with the useEffect hook inside jest.
What happened:
The useEffect hook is not executed correctly inside a jest environment after calling render(<Test />). However it appears to be working correctly if it is called directly in a browser environment.
Reproduction:
Working example: https://codesandbox.io/s/l947z8v6xq (index.js) Not working example in jest: https://codesandbox.io/s/7k5oj92740 (index.test.js)
Problem description:
The useEffect hook should have been executed after the render call
Issue Analytics
- State:
- Created 5 years ago
- Reactions:14
- Comments:32 (16 by maintainers)
Top Results From Across the Web
Function call inside useEffect not firing in jest test
I have a component that, on button click sends the updated value to parent via props.OnValChange . This is implemented in the useEffect...
Read more >useEffect – How to test React Effect Hooks - cultivate
Learn how to test a useEffect hook, how to handle infinite rendering loops, how to deal with a not wrapped in act(..) warning,...
Read more >Understanding Act function | React Native Testing Library
When testing without act call wrapping rendering call, we see that the assertion runs just after the rendering but before useEffect hooks effects...
Read more >Guide of Testing React Components with Hooks & Mocks
Having strong unit tests prevents future emergencies, urgent bug fixes, ... useEffect is not supported by Enzyme's shallow rendering. jest.
Read more >Testing Recipes - React
This page assumes you're using Jest as a test runner. ... Some modules might not work well inside a testing environment, or may...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
That’s because React doesn’t run the hook in sync mode. If you rerender the component the second time, it changes
atotrue: https://codesandbox.io/s/m5m5yqrr18For some reason, this workaround:
changes nothing to my Jest tests, effects just never happen. Only manual replacement of
useEffectwithuseLayoutEffectin components does the trick. I know it’s not a QA thread, but maybe other people are experiencing the same… so any help will be appreciated.