使用 Jest + 测试库测试 Nextjs <Link />

Raf*_*des 10 jestjs next.js react-testing-library

当我测试<Link />行为,期望它重定向到某个路由时,出现了 TypeError ( Cannot read property 'push' of null)。

这是我当前正在测试的组件:

import React from "react"
import Link from "next/link"

const Sandbox = () => {
  return (
    <div>
      <Link href="/about">
        <a data-testid="mytest">Click Me</a>
      </Link>
    </div>
  )
}

export default Sandbox
Run Code Online (Sandbox Code Playgroud)

这是我正在运行的测试:

import React from "react"
import { render, fireEvent } from "@testing-library/react"
import { useRouter } from "next/router"
import Sandbox from ".."

jest.mock("next/router", () => ({
  useRouter: jest.fn(),
}))

describe("Sandbox", () => {
  it.only("should navigate accordingly", () => {
    const push = jest.fn()
    useRouter.mockImplementationOnce(() => ({
      asPath: "/",
      push,
    }))

    const { getByTestId } = render(<Sandbox />)

    const mytest = getByTestId("mytest")
    fireEvent.click(mytest)
    expect(push).toHaveBeenCalledWith("/about")
  })
})
Run Code Online (Sandbox Code Playgroud)

我相信我已经嘲笑了我需要的一切,所以我真的不明白为什么路由器实际上不能“推送”。我在这里缺少什么?

Cam*_*iEQ 2

事实证明,必须模拟的模块略有不同(https://github.com/vercel/next.js/issues/7479#issuecomment-797811147

我自己也遇到过这个问题,所以根据我的一项测试,应该运行:


import { render, fireEvent, screen } from "@testing-library/react"
import { useRouter } from "next/router"
import Sandbox from ".."
  
jest.mock("next/dist/client/router", () => ({
   useRouter: jest.fn(),
}))
 
describe("Sandbox", () => {
  const mockPush = jest.fn(() => Promise.resolve(true));
   
  beforeAll(() => {
    useRouter.mockReturnValue({
      asPath: "/",
      query: {},
      push: mockPush,
      prefetch: () => Promise.resolve(true)
    })
  })
    
  test("should navigate accordingly", () => {
    
    render(<Sandbox />)
   
    const mytest = screen.getByTestId("mytest")
    fireEvent.click(mytest)
   
    expect(mockPush).toHaveBeenCalledWith("/about", expect.anything(), expect.anything())
  })
})

Run Code Online (Sandbox Code Playgroud)

我添加了expect.anything(),因为push可以使用其他参数调用该函数(https://nextjs.org/docs/api-reference/next/router#routerpush