CodePark/ questions / Mocks, spies & timers
START PRACTICINGPRACTICE
Frontend question · Testing › Mocks, spies & timers

After adding jest.useFakeTimers(), this test times out at await user.click(...). What's the fix?

jest.useFakeTimers();
const user = userEvent.setup();
render(<Toast />);
await user.click(screen.getByRole("button", { name: /show/i }));
Create the instance with userEvent.setup({ advanceTimers: jest.advanceTimersByTime })

Create the instance with userEvent.setup({ advanceTimers: jest.advanceTimersByTime }). user-event waits between actions using timers. With fake timers, those timers never fire, so the click promise never resolves. The advanceTimers option tells user-event how to move the fake clock forward. The tempting jest.runAllTimers() option doesn't help. The waiting starts during the click, so running timers before it changes nothing.