scottrippey / next-router-mock

Mock implementation of the Next.js Router

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Issues with Jest.mock: "cannot read properties of null (reading 'pathname')"

KathrynCrawford opened this issue · comments

Since NextJS doesn't have native active links, I am using the router to detect the current pathname and make sure it matches up to the Next Link href.

Component:

const router = useRouter();
const isActive = router.pathname === href;

In the test, I am mocking the router and setting the current url, but pathname is still undefined when I run the test, causing it to fail. "TypeError: Cannot read properties of null (reading 'pathname')"

Test:

import React from 'react';
import { render, screen } from '@testing-library/react';
import { faSearch } from '@fortawesome/pro-light-svg-icons';
import mockRouter from 'next-router-mock';
import { NavLink } from './NavLink';

jest.mock('next/dist/client/router', () => require('next-router-mock'));

describe('NavLink', () => {
  beforeEach(() => {
    mockRouter.setCurrentUrl('/initial');
  });

  it('should render the link label', () => {
    render(
      <NavLink
        icon={faSearch}
        label="Jobs"
        isActive={false}
        collapsed={false}
        href="/"
      />
    );

    const link = screen.getByText('Jobs');

    expect(link).toBeInTheDocument();
  });
});

I'm currently on vacation without access to my computer, so I won't be able to test this until next week.

However I have some thoughts...

Most likely, this error is because the jest.mock call isn't working. This library would never return null from useRouter, but that is what the native Next would do in a unit test.

What version of Next are you using? If they recently changed the path of next/dist/client/router, then maybe that's the issue.

It also might help if you add another mock for jest.mock('next/router' , ... ... But that might only help for your error, but wouldn't help with next/link. Let me know if this helps.