reactjs useNavigate在React测试模拟上不起作用

w41d8nur  于 2023-01-25  发布在  React
关注(0)|答案(1)|浏览(131)

我尝试模拟useNavigate with jest的实现,使用react测试库测试组件,但是当我运行测试jest时,无法识别模拟的函数。
这是零件。

import * as React from "react";
import AppBar from "@mui/material/AppBar";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import { useNavigate } from "react-router-dom";
import { Button } from "@mui/material";
import Somelogo from "../../assets/some-logo.svg";

export default function NavBar() {
  const navigate = useNavigate();
  return (
    <AppBar color="primary" position="sticky">
      <Toolbar>
        <img
          width="100%"
          style={{ maxWidth: "50px" }}
          height="auto"
          src={Somelogo}
          alt="some logo"
        />
        <Typography
          variant="h6"
          component="div"
          sx={{ flexGrow: 1, textAlign: "center" }}
        >
          E-core Breakdown
        </Typography>
        <Button color="info" onClick={() => navigate("/")}>
          Home
        </Button>
        <Button color="info" onClick={() => navigate("/accounts")}>
          Accounts
        </Button>
      </Toolbar>
    </AppBar>
  );
}

这是我试卷

import userEvent from "@testing-library/user-event";
import { render, screen } from "../../utils/test.utils";
import Navbar from "../navbar";

const mockedUsedNavigate = jest.fn();

jest.mock("react-router", () => ({
  ...(jest.requireActual("react-router") as any),
  useNavigate: () => mockedUsedNavigate,
}));

describe("<Navbar />", () => {
  beforeEach(() => {
    mockedUsedNavigate.mockReset();
  });

  test("should navigate to the correct page", () => {
    render(<Navbar />);

    const accountButton = screen.getByText("Accounts", { exact: false });

    userEvent.click(accountButton);

    expect(mockedUsedNavigate).toHaveBeenCalledTimes(1);
  });
});

当我运行这个测试的时候,它告诉我测试失败了。我读了一些文档,看到了使用完全相同的模拟的例子,但是对我来说它不起作用。
failed test

afdcj2ne

afdcj2ne1#

我发现我做错了什么,我需要等待预期的结果发生,在测试中增加了等待。

import userEvent from "@testing-library/user-event";
import { render, screen } from "../../utils/test.utils";
import Navbar from "../navbar";

const mockedUsedNavigate = jest.fn();

jest.mock("react-router", () => ({
  ...(jest.requireActual("react-router") as any),
  useNavigate: () => mockedUsedNavigate,
}));

describe("<Navbar />", () => {
  beforeEach(() => {
    mockedUsedNavigate.mockReset();
  });

  test("should navigate to the correct page", () => {
    render(<Navbar />);

    const accountButton = screen.getByText("Accounts", { exact: false });

    userEvent.click(accountButton);

    await waitFor(() => expect(mockedUsedNavigate).toHaveBeenCalledTimes(1));
  });
});

相关问题