简体   繁体   English

如何在玩笑中覆盖 useParams 的默认模拟

[英]How to override default mock of useParams in jest

I have to test a component which renders based on the country and language in the url path params.我必须测试一个基于 url 路径参数中的国家和语言呈现的组件。 So I want to the if the components are rendered properly based on the change in params.所以我想根据参数的变化正确渲染组件。

I am mocking the useParams and setting some required value which works for most of the tests.我是 mocking 的 useParams 并设置了一些适用于大多数测试的必需值。 Now for a specific case, I need to change the param.现在对于特定情况,我需要更改参数。

   jest.mock('react-router-dom', () => ({
      ...jest.requireActual('react-router-dom'),
      useParams: () => ({
        language: 'IT'
      })
    }));

How do I override the language in test?如何覆盖测试中的语言?

Thank you谢谢

Instead of mocking useParams you can use <MemoryRouter initialEntries> , for example:您可以使用<MemoryRouter initialEntries>代替 mocking useParams ,例如:

MyComponent.js

import { useParams } from "react-router-dom";

function MyComponent() {
  const { language } = useParams();
  return (
    <div>
      <h2>My Component page</h2>
      <p>language: {language}</p>
    </div>
  );
}

MyComponent.test.js

import { MemoryRouter } from "react-router-dom";
import { render, screen, fireEvent } from "@testing-library/react";
import "@testing-library/jest-dom";
import App from "./App";

test("Home: Go to `MyComponent: en`", async () => {
  render(
    <MemoryRouter initialEntries={["/"]}>
      <App />
    </MemoryRouter>
  );

  expect(screen.getByText("Home page")).toBeInTheDocument();

  fireEvent.click(screen.getByText("My Component: en"));

  expect(screen.getByText("language: en")).toBeInTheDocument();
  expect(screen.queryByText("language: fr")).not.toBeInTheDocument();
});

test("MyComponent: en", async () => {
  render(
    <MemoryRouter initialEntries={["/myComponent/en"]}>
      <App />
    </MemoryRouter>
  );

  expect(screen.getByText("language: en")).toBeInTheDocument();
});

test("MyComponent: fr", async () => {
  render(
    <MemoryRouter initialEntries={["/myComponent/fr"]}>
      <App />
    </MemoryRouter>
  );

  expect(screen.getByText("language: fr")).toBeInTheDocument();
});

Online demo在线演示

编辑 eloquent-tu-imqcbh

Based on this page on the Jest docs, try the following根据 Jest 文档上的此页面,尝试以下操作

// create a separate mock function that you can access from tests
// NOTE: the name must start with `mock` and is case sensitive 
const mockUseParams = jest.fn().mockReturnValue({
  language: 'IT',
});

// mock the module using the mock function created above
jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'),
  useParams: mockUseParams,
}));

it('should behave differently when the params change', () => {
  mockUseParams.mockReturnValueOnce({
    language: 'EN',
  });

  // test implementation
});

yes Include the Router in your App component;是的 在你的 App 组件中包含路由器; Always render the App component in your tests (never child components like Locations);始终在您的测试中渲染 App 组件(不要像 Locations 这样的子组件); Navigate to your pages in tests by finding and clicking links on the page The positives of this approach: you don't need to read the rest of this post (and your test setup will be less complicated).通过查找并单击页面上的链接导航到您的测试页面 这种方法的优点:您无需阅读本文的 rest(并且您的测试设置将不那么复杂)。 The negatives: you can't immediately load a routing history (the current page and previous pages) in test setup;缺点:您不能在测试设置中立即加载路由历史记录(当前页面和以前的页面); you need to go through all the user interactions to build the history.您需要 go 通过所有用户交互来构建历史记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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