I want to test a cleanup function in the return of useEffect but I’m unable to simulate unmounting a component.
Code I want to test:
useEffect(() => {
() => clearError(); //I can't cover this line
}, []);
What I have tried
1.
let cleanupFunc;
jest.spyOn(React, 'useEffect')
.mockImplementationOnce(jest.fn())
.mockImplementationOnce(jest.fn())
// third useEffect - clear errors
.mockImplementationOnce((func) => {
cleanupFunc = func();
});
render(<Component {...props} />);
cleanupFunc();
Error: TypeError: cleanupFunc is not a function
2.
const { unmount } = render(<Component {...props} />)
unmount()
expect(props.clearError).toHaveBeenCalledTimes(1)
This one is not causing the cleanup function to be executed