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?