When I'm testing the <Link />
behavior, expecting it to redirect to a certain route, there's a TypeError (Cannot read property 'push' of null
).
This is the component I'm currently testing:
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
And this is the test I'm running:
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")
})
})
I believe that I've mocked everything I need, so I don't really understand why the router can't actually "push". What am I missing here?
jest.mock('next/link', () => ({ children }) => children);
...push
wont be called. – Awakeningjest.mock('next/link', () => ({ Link: 'Link',}));
This might not be good way because it can prevent you to test some other things, but maybe it can help you to overcome what you need. – Gadget