我正在测试一个使用React路由器的navbar组件。我正在尝试使用来自createMemoryHistory
包的history
来测试浏览器导航。
我正在使用react-router-dom v 6.3.0
和history 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
中定义它时也是这种类型。
但是,当在history
中定义测试对象时,访问测试中的beforeEach
对象意味着该类型是History
,而不是MemoryHistory
。
这里发生了什么事?为什么在beforeEach
中定义对象而不是在测试本身中定义对象时,类型似乎会发生变化?
发布于 2022-08-19 02:00:56
IDE显示了正确的提示。您可以在另一个词法范围(createMemoryHistory钩子)中使用“beforeEach”返回的内容声明一个常量的“历史”。因此,测试中的“历史”变量是完全不相关的。事实上,它是一个通过web (文档)提供的全局对象“历史”。您会在beforeEach钩子中调用您的变量吗,比如“我的历史”,它只是测试中的“未定义”。
您应该做的是将“历史”声明移到外部范围,在这个范围内,所有测试都可以使用它。例如,在第一个“描述”下面。如果您需要为每个测试重新创建它,您可以将其声明为'let‘,并在beforeEach钩子中重新分配它。
https://stackoverflow.com/questions/73364590
复制相似问题