lundi 17 février 2020

Mocking react-router-dom useHistory and other hooks with jest

I have a CRA and Typescript (.tsx) application. I'm trying to write a test for a component that needs useHistory and useRouteMatch but it return the error: TypeError: Cannot read property 'history' of undefined.

The component:

const SidebarTreeNav: React.FC<Props> = ( { tree, expanded } ) => {
  const history = useHistory();
  let { url } = useRouteMatch();

  const handleClick = useCallback(
    ( path: string ) => history.push(`${ url }/${ path }`),
    [ history ]);

  return (
    <SidebarTreeNavView expanded={ expanded ?? [ '0' ] }>
      <SidebarTreeNavBlock handleClick={ handleClick } tree={ tree } node={ 0 } />
    </SidebarTreeNavView>
  );
};

export default SidebarTreeNav;

The Test:

  beforeEach(() => {
    jest.mock('react-router-dom', () => {
      const originalModule = jest.requireActual('react-router-dom');

      return {
        __esModule: true,
        ...originalModule,
        useRouteMatch: { url: '/entry' },
        useHistory: jest.fn(),
      };
    });

    shallow = createShallow();
    wrapper = shallow(<SidebarTreeNav tree={ [] } />);
  });

  it('<SidebarTreeNav /> should be defined', () => {
    expect(wrapper).toBeDefined();
  });

Aucun commentaire:

Enregistrer un commentaire