繁体   English   中英

useNavigate 不适用于 React 测试模拟

[英]useNavigate doesn’t work on React test mock

我试图用笑话来模拟 useNavigate 的实现,以使用反应测试库测试组件,但是当我运行我的测试笑话时,我无法识别模拟的 function。

这是组件。

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);
  });
});

当我运行这个测试时,它返回给我测试失败。 我阅读了一些文档并看到了使用完全相同的模拟的示例,但对我来说它不起作用。

失败的测试

我发现我做错了什么,我需要等待预期的结果发生,为测试添加一个 waitfor。

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));
  });
});
①如果本文未解决您的问题,请点击查看与本文相关的问题
②如果本文未解决您的问题,请向程序员专用AI小助手提问
暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM