0

I've just started the topic of testing in react, I've been introduced to some aspects of how and why to test in React. Everything's been fine until I wanted to use jest.UseFakeTimers() and jest.runAllTimers() to test if component state changes after and rerenders the component after a second of delay.

Component:

function App() {
  const [ctr, setCtr] = useState(0)
  useEffect(() =>{
    setTimeout(() => setCtr(1), 1000)
  }, [])
  return <div data-testid="timer">{ctr}</div>
}

Test:

it("should tick after one second to new value", () => {
  render(<App></App>);
  const timer = screen.getByTestId("timer");
  expect(timer.innerHTML).toBe("0");
  jest.useFakeTimers();
  expect(timer.innerHTML).toBe("1");
});
Veanty
  • 33
  • 5

1 Answers1

0

There are several problems with your code:

  1. useFakeTimers() replaces global setTimeout() and other timer functions, so it must be called before your tests.

  2. After the rendering you must call runAllTimers() to fast-forward the timers.

  3. Both rendering and runAllTimers() must be wrapped in act().

See the example here.