Functional component that uses useState to increment a counter, can't increment more than once in tests.
I will link to other issues which appear to be either very similar, or actual duplicates. Because every instance I find appears to complicate the issue, I wanted to open this to provide a more simple repro. It shows a simple counter, note that the first 2 tests pass, but the last fails:
https://codesandbox.io/s/staging-forest-iycsj?fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.test.js&previewwindow=tests&theme=dark
I've tried every combination of act() and wrapper.update(), I can conceive of, as well as wrapper.setProps(wrapper.props()). This last one I tried because somewhere in a doc or guide it said that .setProps must be called to force the component to re-render. But because my test doesn't involve changing props, I attempted passing the current props.
Functional component that uses useState in increment a counter should maintain state across each call to onClick handler, and show expected state when inspected through various means, such as .props(), .debug(), .text(), etc.
MacOS Mojave v10.14.6
NodeJS v10.16.3
"enzyme": "3.8.0",
"enzyme-adapter-react-16": "1.7.1",
"jest": "22.4.3",
"react": "16.12.0",
"react-dom": "16.12.0",
| library | version
| ------------------- | -------
| enzyme | 3.8.0
| react | 16.12.0
| jest | 22.4.3
| react-dom | 16.12.0
| react-test-renderer | ^16.8.6
| adapter (below) | 1.7.1
https://github.com/airbnb/enzyme/issues/2305, https://github.com/airbnb/enzyme/issues/1570, https://github.com/airbnb/enzyme/issues/1996. Probably others that I can't quickly find from browser history.
This is not a bug related to Hooks. Here's the same repro with a class: https://codesandbox.io/s/lively-wildflower-rhez6.
Stepping through the debugger, I see that although toTree captures correct props.onClick ([[Scopes]] in Chrome debugger shows count: 1).
However, the next time Enzyme asserts props, it uses the previous props.onClick (which has captured count: 0). Hence the problem. I'm not sure where it fails to update it, but hope this helps.
@robchristian you're using enzyme v3.8, which predates hooks and has had lots of bugs fixed since; can you upgrade to v3.11 and see if the issue still occurs?
However, I see that both sandboxes still fail on 3.11, so I'll dig into this further. Thanks for the repros!
Any update on this @ljharb ?
Most helpful comment
However, I see that both sandboxes still fail on 3.11, so I'll dig into this further. Thanks for the repros!