最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to override default mock of useParams in jest - Stack Overflow

programmeradmin1浏览0评论

I have to test a ponent which renders based on the country and language in the url path params. So I want to the if the ponents 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. 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

I have to test a ponent which renders based on the country and language in the url path params. So I want to the if the ponents 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. 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

Share Improve this question edited May 20, 2022 at 6:21 Andremoniy 35k24 gold badges142 silver badges253 bronze badges asked Dec 6, 2021 at 17:15 Arjun K RArjun K R 4621 gold badge6 silver badges25 bronze badges 1
  • 2 Don't mock what you don't own, try something like stackoverflow./a/65275037/3001761. – jonrsharpe Commented Dec 6, 2021 at 17:16
Add a ment  | 

5 Answers 5

Reset to default 2

Instead of mocking useParams you can use <MemoryRouter initialEntries>, for example:

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

Based on this page on the Jest docs, try the following

// 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 ponent; Always render the App ponent in your tests (never child ponents like 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

发布评论

评论列表(0)

  1. 暂无评论