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.