Skip to content

Component test with setTimeout and vitest fake timers not working #1198

Closed as not planned
@wilcoschoneveld

Description

@wilcoschoneveld
  • @testing-library/react version: 14.0.0
  • Testing Framework and version: vitest 0.29.8
  • DOM Environment: happydom 8.9.0

Relevant code or config:

import { useEffect, useState } from "react";

export default function Timer() {
  const [state, setState] = useState("Start");

  useEffect(() => {
    setTimeout(() => {
      setState("Next");
    }, 1000);
  }, []);

  return <span>{state}</span>;
}
import { vi, expect, test, beforeEach, afterEach } from "vitest";
import { render, screen } from "@testing-library/react";
import Timer from "./Timer";

beforeEach(() => {
  vi.useFakeTimers();
});

afterEach(() => {
  vi.runOnlyPendingTimers();
  vi.useRealTimers();
});

test("timer test", () => {
  render(<Timer></Timer>);

  expect(screen.getByText("Start")).toBeDefined();

  vi.advanceTimersByTime(1000);

  expect(screen.getByText("Next")).toBeDefined();
});

test("sanity check", () => {
  let flag = false;
  setTimeout(() => (flag = true), 1000);

  expect(flag).toBe(false);

  vi.advanceTimersByTime(1000);

  expect(flag).toBe(true);
});

What you did:

Trying to advance fake timers with vitest and update the Timer component according to its useEffect hook.

What happened:

the Timer component is not updated

Reproduction:

https://github.com/wilcoschoneveld/timer-test/tree/b54f14a06b04c3d467ddecfa0d0d5c1f203d1f04

run tests with npx vitest

Problem description:

the Timer component should be updated, as shows when running npm run dev.

the sanity check test shows that the vitest fake timers work.

Could be related to #1197

Suggested solution:

it also does not work with testing-library/react version 13.4.0
not yet

Metadata

Metadata

Assignees

No one assigned

    Labels

    duplicateThis issue or pull request already existsenhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions