Neeraj Sewani
Neeraj Sewani

Reputation: 4287

Next.js router error while testing using React-testing-library

I was just trying to do a preliminary test of rendering a component that is redirecting the user on the basis of the login status and thus using router from next/router in componentDidMount but getting the following error:

No router instance found. You should only use "next/router" inside the client side of your app.

It appears to me that from client side it means using the router or Link has to be used inside of the render method as that is what makes the DOM and other methods like lifecycle, hooks, and server-side doesn't so in those cases it would throw an error.

I know that testing the entire component beats the purpose of unit testing but I wanted to do this anyway. Therefore, I followed this discussion and it appears that the router has to be mocked in order to be used by the React-Testing-Library but none of the solutions work for me.

Here is the code that I tried:

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

Upvotes: 4

Views: 5800

Answers (2)

Will Meier
Will Meier

Reputation: 538

a solution like:

import { useRouter } from 'next/router'
...
jest.mock('next/router', () => ({
    useRouter: jest.fn(),
}))
...
;(useRouter as jest.Mock).mockImplementation(() => ({
    pathname: '/',
    push: mockPush,
}))

will work.

the error you're encountering will be triggered if you do not mock useRouter in the initial mock (i.e.:

...
jest.mock('next/router')
...

Upvotes: 6

Neeraj Sewani
Neeraj Sewani

Reputation: 4287

Mocked the router using the next-router-mock library. Just pasted jest.mock('next/router', () => require('next-router-mock')); before the test and the tests are passing.

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

Although, the test is passing but getting this warning that is not making any sense to me.

 › 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

Assuming that there is a better way to mock the router.

Upvotes: 2

Related Questions