在 Next.js 中使用 Jest 模拟下一个/链接

如何在 Next JS 中用 jest 模拟“next/link”中的 Link 组件,并在单击链接元素后检查重定向路径?

这是一个带有测试的示例组件:

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

  });
});
stack overflow Mock next/link with Jest in Next.js
原文答案

答案:

作者头像

您可以用RouterContext提供商包装测试,并将模拟路由器作为值传递

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');
   });

  });
 });

并在您的utils中创建一个createMockrouter实用程序。

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;