Jest.js 测试中对BrowserRouter的更新未 Package 在操作中

i2byvkas  于 2022-12-08  发布在  Jest
关注(0)|答案(1)|浏览(160)

I'm trying to implement my first tests in react with react-test-library, but I came across this certain problem where there's warning that my component is not wrapped in act(..)

down below is the test that I'm trying to implement

import { BrowserRouter as Router } from "react-router-dom";
  beforeEach(() => {
    container = render(
      <Router>
        <Search />
      </Router>
    );
  });
  it("handleClick", async () => {
    const button = container.getByText("Search");
    const event = fireEvent.click(button);
    expect(event).toBeTruthy();
  });

and Here is the function that I'm trying to test

const handleClick = async () => {
    setLoading(true);
    const data = await movieAPI.fetchMovieByTitle(movie);
    setLoading(false);
    navigate(`/movie/${data.Title}`, { state: data });
  };
5gfr0r5j

5gfr0r5j1#

结果是,在执行Assert之前,我们需要等待组件更新完全完成,方法是waitFor

it("should render spinner", async () => {
    const button = container.getByText("Search");
    const event = await fireEvent.click(button);
    const spinner = container.getByTestId("spinner");
    await waitFor(() => {
      expect(spinner).toBeInTheDocument();
    });
  });

相关问题