【发布时间】:2021-02-07 19:54:17
【问题描述】:
对于其他组件的单元测试,我使用 spyOn 和 history 模块:
import { render, screen } from "@testing-library/react";
import { createMemoryHistory } from "history";
import { Router } from "react-router-dom";
import Home from "./pages/Home";
test("home", () => {
const history = createMemoryHistory();
const pushSpy = jest.spyOn(history, "push");
render(
<Router history={history}>
<Home />
</Router>
);
userEvent.click(screen.getByRole("button"));
expect(pushSpy).toHaveBeenCalled();
}
我有以下组件,我想在其中测试对history.push() 的调用:
function App() {
return (
<Router>
<Switch>
<Route path="/">
<Home /> //this component uses history.push internally but it is not wrapped in a router
</Route>
</Switch>
</Router>
)
}
当我无法用我的自定义<Router history={history}> 包装App 组件时,我如何spyOn history 对象?
【问题讨论】:
标签: reactjs react-router jestjs