【问题标题】:How to test Router.push with Jest/React如何使用 Jest/React 测试 Router.push
【发布时间】:2019-03-04 15:17:02
【问题描述】:

我还是单元测试的新手,我很难理解如何测试/模拟来自路由器的推送,

<Tab label="Members" alt="Members" onClick={() => Router.push('/members')}/>

上面的行是我需要测试的,但我怎么能呢?我会创建一个假端点然后测试 onClick 吗?

【问题讨论】:

  • 你能告诉我们Router来自哪里吗?
  • 从'next/router'导入路由器;

标签: javascript reactjs jestjs


【解决方案1】:

最简单的方法是像这样模拟路由器

import Router from 'next/router'
jest.mock('next/router', ()=> ({push: jest.fn()}))

模拟点击Tab后,您可以像这样检查电话

expect(Router.push).toHaveBeenCalledWith('/members')

【讨论】:

    【解决方案2】:

    就我而言,我使用的是next/router 中的useRouter,我使用以下方法解决了它:

    
    import { useRouter } from 'next/router'
    
    jest.mock('next/router', () => ({
      __esModule: true,
      useRouter: jest.fn()
    }))
    
    describe('XXX', () => {
      it('XXX', () => {
        const mockRouter = {
          push: jest.fn() // the component uses `router.push` only
        }
    
        (useRouter as jest.Mock).mockReturnValue(mockRouter)
    
        expect(mockRouter.push).toHaveBeenCalledWith('/hello/world')
      })
    })
    

    原答案:https://github.com/vercel/next.js/issues/7479#issuecomment-626297880

    【讨论】:

      【解决方案3】:

      我收到了TypeError: Cannot read property 'push' of undefined triny 来模拟 useRouter 的推送。这个解决方案对我有用:

      1. 首先模拟useRouter
      import { useRouter } from "next/router";
      
      jest.mock("next/router", () => ({
        useRouter: jest.fn(),
      }));
      
      1. 然后在测试块中像这样使用
      const push = jest.fn();
      
      (useRouter as jest.Mock).mockImplementation(() => ({
        push,
      }));
      
      userEvent.click(screen.getByRole("button", { name: 'Move to another route' }));
      expect(push).toHaveBeenCalledWith("/your-expected-route");
      

      在这里找到这个答案:https://github.com/vercel/next.js/issues/7479#issuecomment-778586840

      【讨论】:

        猜你喜欢
        • 2019-07-27
        • 2015-10-12
        • 2019-04-22
        • 2020-10-26
        • 2022-06-11
        • 2021-06-04
        • 2020-05-08
        • 2021-07-29
        • 2021-06-14
        相关资源
        最近更新 更多