How to test components using new react router hooks?

后端 未结 6 512
庸人自扰
庸人自扰 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:52

    If you're using react-testing-library for testing, you can get this mock to work like so.

    jest.mock('react-router-dom', () => ({
        ...jest.requireActual('react-router-dom'),
        useLocation: () => ({ state: { email: 'school@edu.ng' } }),
    }));
    
    export const withReduxNRouter = (
        ui,
        { store = createStore(rootReducer, {}) } = {},
        {
        route = '/',
        history = createMemoryHistory({ initialEntries: [ route ] }),
        } = {}
    ) => {
        return {
        ...render(
            
            {ui}
            
        ),
        history,
        store,
        };
    };
    

    You should have mocked react-router-dom before it has been used to render your component. I'm exploring ways to make this reusable

提交回复
热议问题