CodeyMaze
Mar 16, 2023

Fix Issue : Cannot read property ‘asPath’ of null while calling render in jest

This error usually occurs when using the next/router module in a test file without properly mocking it. Here's how you can fix it:

  1. Create a mock implementation of next/router:
// __mocks__/next/router.js
export default {
useRouter: () => ({
asPath: '/',
}),
};

2. Import the mock implementation in your test file:

// your test file
import { render } from '@testing-library/react';
import Router from 'next/router';

// Import the mock implementation
jest.mock('next/router');

// Your test code
test('...', () => {
render(<Component />);
// ...
});

By mocking next/router, you are providing a mock implementation of useRouter that returns an object with the asPath property set to '/'. This allows the render function to run without throwing the error you encountered.

CodeyMaze
CodeyMaze

Written by CodeyMaze

Crafting Solutions Through Code & Words https://codeymaze.com Feel free to follow me :)

Responses (1)