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.
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.
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).
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With