Home > database >  Can't test timer in react using vitest (jest)
Can't test timer in react using vitest (jest)

Time:09-08

I have this simple component in react and I want to test it but I cannot find a way to mock the setInterval in order to trigger the timer.
The count value is 0 all the time but when I run the component it's working.

UPDATE: I've added this sample respository on stackblitz for running this test.
This is my test file:

import {
  render,
  screen
} from "@testing-library/react";
import React, { useEffect, useState } from "react";
import { expect, test, vi } from "vitest";

function Timer() {
  const [count, setCount] = useState(0)
  useEffect(() => {
    let timer = setInterval(() => {
      setCount(v => v   1)
    }, 1000)
    return () => clearInterval(timer)
  }, [])
  return <div>{count}</div>
}
test("should render correctly", () => {
    vi.useFakeTimers();
    render(<Timer />);
    vi.advanceTimersByTime(2000);
    screen.debug();
    expect(screen.getByText("2")).toBeDefined();
});

CodePudding user response:

The problem was with vitest not being able to notice the dom changes made during the test. The dom update code should be wrapped within an act method from react-dom/test-utils.

So vi.advanceTimersByTime(2000); must be in act.

Theis is the link to the guthub issue I opened for this problem

  • Related