jest-react-hooks-shallow icon indicating copy to clipboard operation
jest-react-hooks-shallow copied to clipboard

useEffect cleanup function is not called on component unmount

Open kvet opened this issue 4 years ago • 6 comments

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

kvet avatar Apr 16 '20 13:04 kvet

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.

mikeborozdin avatar Apr 18 '20 07:04 mikeborozdin

Hi @mikeborozdin ,

I didn't notice this. However, maybe it is possible to at least export some function to perform a manual cleanup?

kvet avatar Apr 18 '20 08:04 kvet

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?

mikeborozdin avatar Apr 21 '20 20:04 mikeborozdin

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).

kvet avatar Apr 27 '20 10:04 kvet

:+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.

MilosRasic avatar Aug 12 '20 14:08 MilosRasic

@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.

mikeborozdin avatar Oct 06 '20 21:10 mikeborozdin