【问题标题】:How to spy on history object from outside the component that uses Router?如何从使用路由器的组件外部监视历史对象?
【发布时间】:2021-02-07 19:54:17
【问题描述】:

对于其他组件的单元测试,我使用 spyOnhistory 模块:

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

当我无法用我的自定义&lt;Router history={history}&gt; 包装App 组件时,我如何spyOn history 对象?

【问题讨论】:

    标签: reactjs react-router jestjs


    【解决方案1】:

    我通过将自定义 history 对象放在我在测试文件和组件文件中导入的文件中来使其工作:

    //testutils.js
    
    import { createMemoryHistory } from "history";
    
    const history = createMemoryHistory();
    
    export default history;
    

    我在App 中导入自定义history 对象:

    //App.jsx
    
    import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
    import history from "./testutils";
    
    function App() {
     return (
      <Router history={history}>
       <Switch>
        <Route path="/">
         <Home /> //this component uses history.push internally but it is not wrapped in a router
        </Route>
       </Switch>
      </Router>
     )
    }
    
    

    我还在我的测试文件中导入了自定义的history 对象,这样我就可以spyOn 相同的对象:

    import history from "./utils/history";
    import { render } from "@testing-library/react";
    import App from "./outsidehistory";
    
    test("Spy on history from utils file", () => {
      const pushSpy = jest.spyOn(history, "push");
      render(<App />);
      expect(pushSpy).toHaveBeenCalledWith("/success");
    });
    
    

    【讨论】:

    • 间谍的目的是什么?由于您可以访问正在使用的history,因此您可以断言其状态。
    • 请注意,您现在有一个从“test utils”在您的生产代码中的导入。将路由器 out 移出 App.js 会容易得多。
    猜你喜欢
    • 2017-08-31
    • 2020-01-19
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 2017-06-11
    • 2021-09-29
    • 1970-01-01
    相关资源
    最近更新 更多