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