简体   繁体   中英

Mock next/link with Jest in Next.js

How to mock the Link component from "next/link" with jest in Next JS and check the redirect path after a click on a link element?

Here an example component with a test:

import Link from "next/link";

export default function Nav() {
  return (
    <div>
      <Link href="/login">
        <span>Click here</span>
      </Link>
    </div>
  )
}
describe("Nav", () => {
  it("redirects correctly", async () => {
  render(<Nav />)

  fireEvent.click(screen.getByText("Click here"));

  // check if redirect to href prop works as expected

  });
});

You may wrap your test with RouterContext provider and pass the mock router as a value

import createMockRouter from 'src/test-utils/createMockRouter';
import { RouterContext } from 'next/dist/shared/lib/router-context';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';

describe("Nav", () => {

let router = createMockRouter({});

 it("redirects correctly", async () => {
  render(
   <RouterContext.Provider value={router}>
     <Nav />
   </RouterContext.Provider>)

   waitFor(() => {
    fireEvent.click(screen.getByText("Click here"));
    expect(router.push).toHaveBeenCalledWith('/login');
   });

  });
 });

And create a createMockRouter utility in your utils like this.

import { NextRouter } from 'next/router';

const createMockRouter = (router: Partial<NextRouter>): NextRouter => {
 return {
   basePath: '',
   pathname: '/',
   route: '/',
   query: {},
   asPath: '/',
   back: jest.fn(),
   beforePopState: jest.fn(),
   prefetch: jest.fn(),
   push: jest.fn(),
   reload: jest.fn(),
   replace: jest.fn(),
   events: {
     on: jest.fn(),
     off: jest.fn(),
     emit: jest.fn(),
   },
   isFallback: false,
   isLocaleDomain: false,
   isReady: true,
   defaultLocale: 'en',
   domainLocales: [],
   isPreview: false,
   ...router,
 };
};
export default createMockRouter;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM