27

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.

1
  • 2
    did you try wrapper.unmount() (enzyme method) ? It would be better if you can give code sandbox link with test case you have written. Easy to fix or help. Commented Oct 2, 2019 at 7:25

7 Answers 7

26

I would suggest you checkout react-testing-library. The library offers a unmount method, that gets returned from its render method. After calling unmount(), you can check if the listeners have been removed. In general, I can very much recommend react-testing-library. We use it for all our frontend tests in combination with jest and it works like a charm.

Sample usage of the unmount method:

import { render } from "@testing-library/react";

it("Should do what I want", () => {
  const { unmount } = render(
    <MyComponent value="test" } />
  );

  unmount();

  // ... expects
});
2
  • 2
    did you verify if this works? For me the unmount does not call any of the cleanup functions from useEffect
    – Vimil Saju
    Commented Dec 13, 2022 at 17:40
  • It did work back then and I don't see why it shouldn't now. Commented Jan 2, 2023 at 7:50
14

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();
1
  • 3
    This workaround doesn't allow specifying dependencies for useEffect, and it also won't work if useEffect is imported directly instead of used as React.useEffect.
    – slikts
    Commented Jul 22, 2021 at 7:41
6

Here is the complete answer that solves my problem:

it('Should run useEffect cleanUp return function', () => {
  const remover = jest
    .spyOn(global, 'removeEventListener')
    .mockImplementation(() => {});
  act(() => {
    component = mount( < MyComponent value = "Test" / > );
  });
  component.unmount();

  expect(remover).toHaveBeenCalled();
});
2
  • component.unmount() did it for me. thanks!
    – uandrew
    Commented Dec 10, 2021 at 15:23
  • This worked great for me! I didn't even need to use "act()". Commented Nov 29, 2023 at 1:30
5

To those of you who, like me, could not make the accepted answer work:

jest.spyOn(React, "useEffect").mockImplementationOnce(cb => cb()());

Adding the second () to the callback worked to execute the cleanup.

1
  • This worked for me (as did the accepted answer). One to note though, typescript isn't happy: This expression is not callable. Not all constituents of type 'void | Destructor' are callable. Type 'void' has no call signatures.
    – tallpaul
    Commented Nov 29, 2022 at 14:47
2

Building on the answer from @thomas-rufflo it's worth pointing out that:

import { useEffect } from 'react';

Doesn't work. You have to use:

React.useEffect

Taken from this blog post: https://blog.carbonfive.com/shallow-testing-hooks-with-enzyme/

I'm new to front-end testing so this tripped me up for some time!

0

I saw this work-around on GitHub from a testing-library/react contributor. Here's what it looks like:

it('should reset API state on unmount', () => {
    let cleanupFunc;

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

    const { unmount } = renderHook(() => useLogin({ onLoggedIn: onLoggedInMock, onPasswordChange: onPasswordChangeMock }));
    unmount();
    cleanupFunc();
    expect(resetOneApiState).toHaveBeenCalled();
  });

Here the useEffect that I'm testing:

import { useEffect } from 'react';

useEffect(() => {
    function handleResetOneApiState() {
      dispatch(resetOneApiState({ api: 'userLogin' }));
    }
    return () => {
      handleResetOneApiState();
    };
  }, []);
-2

React doesn't run the hook in sync mode. https://codesandbox.io/s/m5m5yqrr18

import React from "react";
import { cleanup, render } from "react-testing-library";

afterEach(cleanup);

it("React test", () => {
  let a = false;
  function Test() {
    React.useEffect(() => {
      a = true;
    });
    return <div>Hello World</div>;
  }
  const { rerender } = render(<Test />);
  rerender(<Test />);
  expect(a).toBe(true);
});

2
  • Thank you, will it cover both onScroll and resize methods? Will try now Commented Oct 2, 2019 at 3:04
  • Tried your solution as you suggested, still it doesn't cover my use case Commented Oct 2, 2019 at 4:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.