2

I want to test a react component that reads search params from the url. This is the component (the full content is sanitized to focus on the main problem) that reads a param from the url localhost:2000/#/list?ids=001,002:

import { useSearchParams } from 'react-router-dom';

function List() {
  const [searchParams] = useSearchParams();
  const idsString = searchParams.get('ids');
  const ids = idsString?.split(',') || [];

  return (
    <div>{ids}</div>
  );
}

I am stuck at the point where I have to render the component whilst passing the url params at the same time. Here is my test in vitest:

import { render, screen } from '@testing-library/react';
import List from './List';

describe('List', () => {
  test('show list of ids when provided the ids from the url', async () => {
    render(<List />);
    expect(await screen.findByText('001,002')).toBeInTheDocument());
  });
});

How can I include the url params in the test? Will I have to mock useSearchParams and how can I mock it if it is the only way?

Lemour
  • 71
  • 1
  • 6
  • 2
    I recommend looking into `MemoryRouter` from `react-router-dom`. See https://stackoverflow.com/questions/69878146/how-can-i-test-react-router-with-jest and https://reactrouter.com/en/main/router-components/memory-router for more details and suggestions. – Code-Apprentice Apr 21 '23 at 07:31
  • 1
    You won't necessarily need to mock `useSearchParams()` directly. But you will need to wrap your `` in a proper provider (maybe indirectly using a router) for the hook to work correctly in the context of your test. – Code-Apprentice Apr 21 '23 at 07:32

1 Answers1

1

In the test, you only instantiate the component itself and do not actually specify/query a URL. It may be possible to mock the URL, or better only those parameters. But as it stands, your test cannot draw any parameters from the URL.

If you have jest at hand you can use sth. like:

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'),
  useSearchParams: () => [new URLSearchParams({ ids: '001,002' })],
}));
JaB
  • 310
  • 4
  • 15