Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock useSearchParams react testing library

I have this custom hook

import { useLocation, useNavigate, useSearchParams } from "react-router-dom";

const useZRoutes = () => {
  const navigate = useNavigate();
  const { search, hash } = useLocation();
  const [searchParams, setSearchParams] = useSearchParams();

  return {
    getQueryParam: <T>(key: string): T | null => {
      if (searchParams.has(key)) {
        const value = searchParams.get(key);
        return value as unknown as T;
      }

      return null;
    },
    deleteQueryParam: (key: string): void => {
      if (searchParams.has(key)) {
        searchParams.delete(key);
        setSearchParams(searchParams);
      }
    },
    extendsNavigate: (pathname: string) => navigate({ pathname, search, hash }),
  };
};

export { useZRoutes };

Now, I need to test the getQueryParam function but I can't update the URL with query param.

I tried to mock useSearchParams with Object.defineProperty and with jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), // use actual for all non-hook parts useSearchParams: () => ("pid=123"), }));

and my test isn't passed. what should I do?

like image 445
Maor Bar Avatar asked Sep 13 '25 11:09

Maor Bar


1 Answers

Instead of attempting to mock useSearchParams, I would recommend wrapping a component that is using your custom hook with a MemoryRouter and passing in your search params as initialEntries.

import { MemoryRouter } from 'react-router-dom'
import { render } from '@testing-library/react'

describe('My component using the useZRoutes hook', () => {    
  it('should do something', () => {
    render(
      <MemoryRouter initialEntries={["?pid=123"]}>
        <TestComponentUsingHook />
      </MemoryRouter>
    )
    // expect something
  })
})
like image 55
Fraser Crosbie Avatar answered Sep 15 '25 01:09

Fraser Crosbie