jest-react-hooks-shallow
jest-react-hooks-shallow copied to clipboard
useEffect cleanup function is not called on component unmount
I am using useEffect
in my test component.
const Cmp = () => {
React.useEffect(() => {
console.log(1);
return () => console.log(2);
}, []);
return <span>Test</span>;
};
And in test: shallow(<Cmp />).unmount()
.
And there is no log emitted in the cleanup function
Hi @kvet ,
Thank you for submitting the issue. Unfortunately, as the FAQ says the library has no way of trigger cleanup functions when a component unmounts. The cleanup functions are only called before invoking the same effect again.
Hi @mikeborozdin ,
I didn't notice this. However, maybe it is possible to at least export some function to perform a manual cleanup?
Hi @kvet ,
Do you have an example on how the code doing that would look like? What are you trying to achieve?
If you have to invoke a cleanup manually in a test, is there much point in testing it?
In my scenario, I want to test cleanup function on unmount. So, that unmount is already done with wrapper.unmount()
method. And it should not be a problem for those who really want to test this, call an additional method here like cleanupReactHooks()
.
This of course can cause problems with multiple components testing on the one test. But I guess we can provide wrapper instance to that method in order to call hooks cleanups for specific component. Something like cleanupReactHooks(forWrapper)
.
:+1: for this
In my case, I'm trying to test an event listener attached to document
in an effect. Without cleanup on unmount, every test case will add another listener to document
which will never be cleaned up. Makes toHaveBeenCalledTimes()
really unpredictable.
@kvet ,
That's an interesting proposal! I'll look into it. It might be difficult to implement cleanupReactHooks(forWrapper)
, since the library has no knowledge of components on Enzyme wrappers. But I can certainly add a method for firing all cleaning up functions.