I have small hook that I wrote to avoid re-rendering when the component is unmounted.
it("should work and not rerender and unmount later", () => {
jest.useFakeTimers('modern');
function MyComponent() {
const [foo, setFoo] = useStateIfMounted("bar");
useEffect(() => {
(async () => {
await delay(5000);
setFoo("brin");
})();
}, [])
useEffect(() => {
(async () => {
await delay(10000);
setFoo("BAZ");
})();
}, [])
return ({foo});
}
const { getByTestId, queryByTestId, unmount } = render( )
expect(getByTestId("test").textContent).toEqual("bar");
act(() => jest.advanceTimersByTime(4999));
expect(getByTestId("test").textContent).toEqual("bar");
// the following triggers a state change
// and I get Warning: An update to MyComponent inside a test was not wrapped in act(...).
act(()=>jest.advanceTimersByTime(1));
// expect(getByTestId("test").textContent).toEqual("brin");
// unmount();
// act(()=>jest.advanceTimersByTime(5000));
// expect(queryByTestId("test")).toBeFalsy()
})
I get
at the point where I would expect it to have a state change but I already wrapped it in act
act(()=>jest.advanceTimersByTime(1));
