【问题标题】:Next.js router error while testing using React-testing-library使用 React-testing-library 进行测试时出现 Next.js 路由器错误
【发布时间】:2021-09-24 15:55:46
【问题描述】:

我只是在尝试渲染一个组件的初步测试,该组件根据登录状态重定向用户,因此在componentDidMount 中使用next/router 中的router,但出现以下错误:

未找到路由器实例。 您应该只在应用的客户端内使用“next/router”。

在我看来,从 client 端 这意味着使用 routerLink 必须在 render 方法内部使用,因为是什么使得 DOM 和其他方法(如生命周期、钩子和服务器端)在这些情况下不会抛出错误。

我知道测试整个组件胜过单元测试的目的,但我还是想这样做。因此,我关注了这个discussion,看来必须模拟路由器才能被 React-Testing-Library 使用,但没有一个解决方案适合我。

这是我尝试过的代码:

describe('Home Page', () => {
  it('renders without crashing', async () => {
    render(<Home />)
  })
})

【问题讨论】:

    标签: jestjs next.js react-testing-library


    【解决方案1】:

    使用 next-router-mock 库模拟了路由器。刚刚在测试前粘贴jest.mock('next/router', () =&gt; require('next-router-mock'));,测试通过了。

    jest.mock('next/router', () => require('next-router-mock'));
    describe('Home Page', () => {
      it('renders without crashing', async () => {
        render(<Home />)
      })
    })
    

    虽然测试通过了,但收到这个对我来说没有任何意义的警告。

     › 1 snapshot obsolete.
       • Home Page renders without crashing 1
    Snapshot Summary
     › 1 snapshot obsolete from 1 test suite. To remove it, press `u`.
       ↳ tests/homePage.test.js
           • Home Page renders without crashing 1
    

    假设有更好的方法来模拟路由器。

    【讨论】:

      猜你喜欢
      • 2019-07-08
      • 2021-05-25
      • 2019-05-21
      • 2019-11-11
      • 2020-09-28
      • 1970-01-01
      • 2019-09-02
      • 2023-04-04
      • 1970-01-01
      相关资源
      最近更新 更多