Search code examples
reactjsjestjsenzyme

How to unit test useEffect cleanUp return function using Jest and Enzyme


I tried many scenarios but none worked, am facing issues with useEffect Cleanup return method. Looking for some solutions to cover the use case. Not able to attach the screenshot because of less reputation.

I have did some research and followed the solutions provided like creating spyOn, mount, unMount scenarios. But none worked.

useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    window.addEventListener('resize', handleResize);
    return () => {
       window.removeEventListener('scroll', handleScroll);
       window.removeEventListener('resize', handleResize);
    };
}, []);

Expecting test coverage for return statement inside useEffect function.

Please excuse typos - posted from mobile.


Solution

  • In order to run the clean up function you specified in the useEffect hook, you can cache a reference to it and then call that reference later in your test:

    let cleanupFunc;
    
    jest.spyOn(React, "useEffect").mockImplementationOnce(func => {
        cleanupFunc = func();
    });
    
    cleanupFunc();