react-hooks-testing-library: Unmount doesn't seem to be firing useEffect cleanup functions
react-hooks-testing-libraryversion: 8.0.0reactversion: ^17.0.2react-domversion (if applicable): ^17.0.2react-test-rendererversion (if applicable): n/anodeversion: v14.17.6npm(oryarn) version: 6.14.15
Relevant code or config:
The component I’m testing:
import { useState, useEffect } from "react";
const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value]);
return debouncedValue;
};
export default useDebounce;
The test itself:
import { renderHook } from "@testing-library/react-hooks";
import useDebounce from "../useDebounce";
jest.useFakeTimers();
jest.spyOn(global, "clearTimeout");
describe("useDebounce", () => {
test(`it should clear the timeout when unmounting`, () => {
const value = "test";
const delay = 1000;
const { unmount } = renderHook(() => useDebounce(value, delay));
expect(clearTimeout).not.toHaveBeenCalled();
unmount();
expect(clearTimeout).toHaveBeenCalled(); // fails here
});
});
What you did:
I’m attempting to test that the useEffect cleanup function in my hook fires correctly.
What happened:
While it works properly when running normally, I can’t get unmount() to fire it.
Reproduction:
The above example reproduces the problem.
Problem description:
Unmount doesn’t seem to be properly cleanup up useEffects.
About this issue
- Original URL
- State: open
- Created 4 years ago
- Reactions: 15
- Comments: 15 (5 by maintainers)
try skiping one thread cycle before expecting:
@bhushanlaware it looks like you are rendering with
react-testing-library, notreact-hooks-testing-libraryso I suggest raising an issue with them for your case.As a general reminder to others coming into this issue, if you are importing
renderHookfrom@testing-library/reactand not@testing-library/react-hooksthen you should also be raising an issue withreact-testing-libraryinstead of tacking on a +1 to this issue.Also a general suspicion that fake timers, unhandled async or mocked
useEffectimplementations are the likely cause here rather than the testing libraries involved. We generally defer the actual rendering to react itself, so if effects are not being cleanup up, a lot more people would be complaining about it.Hello, if this can be of any help, here is a reproduction code:
Result:
Dependencies:
This code is hosted here: https://github.com/saramorillon/hooks/tree/reproduction-847