test utils broken due to observer map
See original GitHub issueDescribe the bug
There’s a cache of observers here: https://github.com/thebuilder/react-intersection-observer/blob/ef0bb84363601992d55a48e26ee19faeb3dd0303/src/observe.ts#L3
This prevents new IntersectionObservers from being created.
test-utils maintains a map of IntersectionObserver to observed Item: https://github.com/thebuilder/react-intersection-observer/blob/d3608a6b6ed21d6e39daaf65005d99514702ec3f/src/test-utils.ts#L50
Entries are inserted when new IntersectionObservers are constructed. This map is used to iterate over all observers when using the mock functions. However, the map is cleared after every test. Due to the observer cache mentioned above, subsequent tests will reuse an observer which is no longer in the test-utils observer map. This breaks all the mock functions if the same useInView is tested in multiple it
blocks.
To Reproduce Try and recreate the issue in a Codesandbox:
Hopefully the description above is clear enough.
Expected behavior Mock functions should work across multiple tests
Screenshots If applicable, add screenshots to help explain your problem.
Desktop (please complete the following information):
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
Smartphone (please complete the following information):
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
Additional context Add any other context about the problem here.
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (6 by maintainers)
Good catch. Should be simple enough to fix - The
afterEach
needs to callunobserve
on each observer before clearing it.@yepitschunked I’ve reverted the change in #523 -
test-utils
was never suppose to import any of the files, but because it’s compiled with TypeScript it has no knowledge of the bundles.I’ll need to figure out a better way if this is an actual issue. Can you write out the basic steps you take to cause the issue, so I can replicate it in a test - I haven’t actually been able to do it myself.
Reading your description again, I think the issue might be elsewhere - Are the components unmounted after each
it
? https://testing-library.com/docs/react-testing-library/api/#cleanup