1

I developed a project with NextJS. I want to test the pathname of the link in the navbar using Jest and Testing Library but userEvent.click doesn't work. So either the pathname doesn't change, it keeps returning / or userEvent.click doesn't work. How to fix that problem?

Navbar.tsx Component

import Link from 'next/link';
import React from 'react';

const Navbar = () => {
  return (
    <>
      <Link href="/" className="text-3xl font-deca font-extrabold italic" data-testid="logo">
        AvaDronity
      </Link>
      <nav>
        <ul>
          <li>
            <Link href="/drones">drones</Link>
          </li>
          <li>
            <Link href="/cameras">cameras</Link>
          </li>
          <li>
            <Link href="/robots">robots</Link>
          </li>
          <li>
            <Link href="/explore">explore</Link>
          </li>
          <li>
            <Link href="/support">support</Link>
          </li>
        </ul>
      </nav>
    </>
  );
};

export default Navbar;

Navbar.test.tsx File

import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom/extend-expect';
import { createMemoryHistory } from 'history';
import Navbar from './Navbar';

describe('Navbar Component', () => {
  beforeEach(() => {
    render(<Navbar />);
  });

  it('should redirect to url and update history', async () => {
    const {
      location: { pathname },
    } = createMemoryHistory();
    console.log(pathname);

    const user = userEvent.setup();
    await user.click(screen.getByText('drones', { exact: false }));

    console.log(pathname);

    expect(pathname).toEqual('/drones');
  });
});

I've reviewed and tried similar errors and questions from different web sites, but I couldn't get any results.

In the test I wrote, pathname should be updated to /drones as expected after the userEvent.click event.

1 Answer 1

2

I faced the same problem but was able to overcome it with fireEvent for the Next Link component specifically. So in theory, the following code should work for you --

fireEvent.click(screen.getByText('drones', { exact: false }));

While knowing that userEvent is a preferred way to simulate user interaction, I wasn't able to find any other ways to get it working and fell back to fireEvent as the last resort.

Hope this helps.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.