React router 和 createMemoryHistory(测试中):当 beforeEach 中定义历史记录时,属性'location'在类型 'History' 上不存在



我正在测试一个使用React Router的导航栏组件。我正在尝试使用history包中的createMemoryHistory来测试浏览器导航。

我正在使用react-router-dom v 6.3.0history v 5.3.0

我的测试是这样的:

import { render, screen } from "@testing-library/react";
import React from "react";
import { Router } from "react-router-dom";
import { createMemoryHistory } from "history";
import { NavBarComponent } from "../navBarComponent";
import userEvent from "@testing-library/user-event";

describe("<NavBarComponent/>", () => {
beforeEach(() => {
const history = createMemoryHistory({ initialEntries: ["/"] });
render(
<Router location={history.location} navigator={history}>
<NavBarComponent></NavBarComponent>
</Router>
);
});
describe("Clicking on buttons to change route", () => {
it("navigates to correct paths", () => {
expect(history.location.pathname).toBe("/"); // <----- IDE error is here: Property 'location' does not exist on type 'History'
userEvent.click(screen.getByText("Collection"));
expect(history.location.pathname).toBe("/collection");
});
});
});

运行测试会出现以下错误:

TypeError: Cannot read properties of undefined (reading 'pathname')
36 |       //   </Router>
37 |       // );
> 38 |       expect(history.location.pathname).toBe("/");

然而,当我将beforeEach代码分解为每个单独的测试时,测试工作正常:

import { render, screen } from "@testing-library/react";
import React from "react";
import { Router } from "react-router-dom";
import { createMemoryHistory } from "history";
import { NavBarComponent } from "../navBarComponent";
import userEvent from "@testing-library/user-event";
describe("<NavBarComponent/>", () => {
describe("Clicking on buttons to change route", () => {
it("navigates to correct paths", () => {
const history = createMemoryHistory({ initialEntries: ["/"] });
render(
<Router location={history.location} navigator={history}>
<NavBarComponent></NavBarComponent>
</Router>
);
expect(history.location.pathname).toBe("/");
userEvent.click(screen.getByText("Collection"));
expect(history.location.pathname).toBe("/collection");
});
});
});

我的IDE表明,当history在测试本身中定义时,它的类型是MemoryHistory,这也是当它在beforeEach中定义时的类型。

但是,当在beforeEach中定义history对象时,访问测试内部的该对象表明该类型是History,而不是MemoryHistory

这是怎么回事?为什么在beforeEach中定义对象时,类型似乎会发生变化,而不是在测试本身内部?

IDE显示正确的提示。您用"createMemoryHistory"在另一个词法作用域(beforeEach hook(中返回的内容声明了一个常量"history"。因此,测试中的"历史"变量是完全无关的。事实上,它是一个全局对象"历史记录",可通过web API(文档(获得。你会在beforeEach钩子中调用你的变量吗?比如"myHistory",它在测试中只是"未定义"的。

您应该做的是将"history"的声明移动到外部范围,在那里它将可用于所有测试。例如,在第一个"description"下。如果您需要为每个测试重新创建它,您可以将它声明为"let",并在beforeEach钩子中重新分配它。

最新更新