Skip to content

why can my code work normally when the code (vi.advanceTimersByTime) is not wrapped in act function? #1183

Description

@sunny15100

the component toast:

import { FC, useState, useEffect } from "react";
export const Toast: FC<{}> = () => {
  const [isVisible, setIsVisible] = useState(true);
  useEffect(() => {
    setTimeout(() => {
      setIsVisible(false);
    }, 1000);
  }, []);
  return isVisible ? <div>Toast!</div> : null;
};

the test file:

import { Toast } from "./toast";
import { render, screen, act } from "@testing-library/react";
import { vi, it, expect } from "vitest";

it("should display Toast in 1 sec", () => {
  vi.useFakeTimers();
  render(<Toast />);
  expect(screen.getByText("Toast!")).toBeInTheDocument();
  vi.advanceTimersByTime(500);
  expect(screen.getByText("Toast!")).toBeInTheDocument();
  vi.advanceTimersByTime(500);
  // act(() => vi.advanceTimersByTime(500));
  expect(screen.queryByText("Toast!")).not.toBeInTheDocument();
});

usually, we should wrap vi.advanceTimersByTime in act function。
but unExpected,if I don't do that,it can pass the test also。why? seemly related to the react version?

the playground:https://codesandbox.io/p/sandbox/toast-test-project-t3zwr0?file=%2Fsrc%2Ftoast.test.tsx&selection=%5B%7B%22endColumn%22%3A1%2C%22endLineNumber%22%3A15%2C%22startColumn%22%3A1%2C%22startLineNumber%22%3A1%7D%5D

the package version is

"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^12.1.5",
"@testing-library/react-hooks": "^8.0.1",
"@testing-library/user-event": "^13.5.0",
"@vitejs/plugin-react": "2.0.1",
"autoprefixer": "10.4.8",
"lodash": "^4.17.21",
"postcss": "8.4.16",
"react": "^17.0.0",
"react-dom": "^17.0.0",
"tailwindcss": "3.1.8",
"vite": "3.0.9",
"vitest": "0.28.5"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions