How to unit test useEffect cleanUp return function using Jest and Enzyme
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
});
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();