使用 Jest + Testing-Library 测试 Nextjs <Link />

时间:2021-02-17 10:09:57

标签: 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

这是我正在运行的测试:

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

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

0 个答案:

没有答案
相关问题