'React testing library - fakeTimers with waitFor/waitForElementToBeRemoved
Last time I have updated testing-library/dom from version 7.29.4 to 8.0.0. After that tests which have jest.useFakeTimers stopped working whenever waitFor/waitForElementToBeRemoved is used.
export default function Test() {
const [loaded, setLoaded] = useState(false);
const getDataCallback = useCallback(() => {
return getData();
}, [])
useEffect(() => {
getDataCallback().then(data => {
setLoaded(true)
});
}, [])
return (
<>
{
loaded ?
<>
{new Date().toDateString()} //displays current date
</>
: <Loader/>
}
</>
)}
Test code:
const mockFunc = jest.spyOn(api, "getData");
const fakeData = [{ date: "2020-01"}, { date: "2020-02"},];
beforeEach(() => {
jest.useFakeTimers("modern").setSystemTime(new Date(2020, 2, 3));
mockFunc.mockResolvedValue(fakeData);
})
it("test", async () => {
render(<Test />);
await waitForElementToBeRemoved(screen.queryByTestId("loader"));
expect(screen.getByText(/tue mar 03 2020/i)).toBeInTheDocument();
})
In this code it's some fake api call, when it's done then we want to display the current date. If the call is not finished, then some loader/spinner is on the screen. When I remove loader state and waitForElementToBeRemoved() from code I have mocked date on the screen and everything works like expected, otherwise real date is displayed.
Solution 1:[1]
I'm not sure what is happening inside of your getData, but if it is using setTimeout or similar, then you need to tell jest to advance the fake timers or flush them.
I had a similar issue where I was using real timers and all tests passed, then when using fake timers they all failed. In my scenario I think it was because my tests were not waiting for the timeout to finish and just immediately executed assertions as if timeouts had passed when they really hadn't. Adding jest.advanceTimersByTime(theSetTimeoutTime) before the calls to waitForElementToBeRemoved fixed my tests in almost all cases.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lokua |
