vendredi 5 février 2021

Testing custom hooks which rely on react-router@6 useSearchParams

I'm trying to test a custom hook which changes the search params and relies on useSearchParams to do this. However, when in the testing environment I'm unsure what to wrap the hook in, in order for it to function as expected. I'm using react-router v6.

customHook:

export const useCustomSearchParams = () => {
  const [searchParams, setSearchParams] = useSearchParams();

  const updateSearchParams = (newSearchParams = {}, clearSearchParams = []) => {
    const searchParamsObject = {};
    for (const [key, value] of params.entries()) {
      searchParamsObject[key] = value;
    }

    clearSearchParams.forEach((key) => delete searchParamsObject[key]);

    setSearchParams({
      ...searchParamsObject,
      ...newSearchParams,
    });
  };

  return [searchParams, updateSearchParams];
};

test:

import { renderHook, act } from '@testing-library/react-hooks';
import { BrowserRouter } from 'react-router-dom';
import { useCustomSearchParams } from './useCustomSearchParams';

it('should add new params', () => {
  const wrapper = ({ children }) = <BrowserRouter>{children}<BrowserRouter />
  const { result } = renderHook(() => useCustomSearchParams(), { wrapper });

  act(() => {
    result.current[1]({ foo: 'bar' });
  });

  expect(mockSetSearchParams).toHaveBeenCalledWith({
    foo: 'bar',
  });
});

This works as far as I can tell but I don't know how to reset the url before each test. So tests after this one will contain foo=bar.

Using jest and testing-library.

Aucun commentaire:

Enregistrer un commentaire