How to test components using new react router hooks?

后端 未结 6 511
庸人自扰
庸人自扰 2020-12-08 01:52

Until now, in unit tests, react router match params were retrieved as props of component. So testing a component considering some specific match, with specific url parameter

6条回答
  •  生来不讨喜
    2020-12-08 02:45

    In your component use hooks as below

    import {useLocation} from 'react-router';
    
    const location = useLocation()
    

    In your test spy on reactRouter Object as below

    import routeData from 'react-router';
    
    const mockLocation = {
      pathname: '/welcome',
      hash: '',
      search: '',
      state: ''
    }
    beforeEach(() => {
      jest.spyOn(routeData, 'useLocation').mockReturnValue(mockLocation)
    });
    

提交回复
热议问题