Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 313
user12133234 Avatar asked Oct 02 '19 01:10

user12133234


People also ask

How do I useEffect with cleanup function?

The hook comes with a cleanup function, which you might not always need, but it can come in handy. To invoke the cleanup function you can simply add a return function like so: useEffect(() => { // Your effect return () => { // Cleanup }; }, []); The cleanup can prevent memory leaks and remove unwanted things.

How do you write test cases for useEffect in Jest?

So I'd put most checks in single test case: it('re-init value for nested input after props changes', () => { const wrapper = mount(<InputComponent />); function getInput(wrapper) { return wrapper. find("input"). prop("value"); } expect(getInput(wrapper).

What is difference between Jest and Enzyme?

Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.


2 Answers

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
});
like image 192
Albert Schilling Avatar answered Sep 21 '22 15:09

Albert Schilling


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();
like image 31
Thomas Rufflo Avatar answered Sep 18 '22 15:09

Thomas Rufflo