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 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