next-router-mock
next-router-mock copied to clipboard
Failed to jest example code on Readme in Next12.1.6
Hello!
I've happened to runtime error with the testing readme.
import singletonRouter from 'next/router';
import NextLink from 'next/link';
import { render, fireEvent, screen, waitFor } from '@testing-library/react';
import mockRouter from 'next-router-mock';
jest.mock('next/router', () => require('next-router-mock'));
// This is needed for mocking 'next/link':
jest.mock('next/dist/client/router', () => require('next-router-mock'));
describe('next-router-mock', () => {
beforeEach(() => {
mockRouter.setCurrentUrl('/initial');
});
it('works with next/link', async () => {
render(
<NextLink href="/example?foo=bar">
<a>Example Link</a>
</NextLink>
);
fireEvent.click(screen.getByText('Example Link'));
await waitFor(() => {
expect(singletonRouter).toMatchObject({
asPath: '/example?foo=bar',
pathname: '/example',
query: { foo: 'bar' },
});
});
});
});
The test fails with the following error:
Error: Uncaught [TypeError: Cannot use 'in' operator to search for 'softPush' in null]
This error occurs with fireEvent.click
My environment follows:
- next-router-mock: 0.7.4
- Next: 12.1.6
- React: 17.0.2
- Jest: 28.1.3
- jest-environment-jsdom: 28.1.3
- @testing-library/jest-dom: 5.16.4
- @testing-library/react": 12.1.5
- @testing-library/user-event": 14.3.0
Solve add the following code to jest.setup.js Thanks for issue #58
jest.mock("next/dist/client/router", () => require("next-router-mock"));
jest.mock("next/dist/shared/lib/router-context", () => {
const { createContext } = require("react");
const router = require("next-router-mock").default;
const RouterContext = createContext(router);
return { RouterContext };
});
This code is quoted from the issue
Closing as duplicate of #58 I'm still considering how to fix this.