Testing react component enclosed in withRouter (preferably using jest/enzyme)
Normally if we try to test such components we won’t be able to render it as it is wrapped within WithRouter (WithRouter is a wrapper over a component which provides Router props like match, route and history to be directly used within the component). module.exports = withRouter(ManageProfilePage);
To render such components, we have to explicitly tell it to render the wrapped component using WrappedComponent keyword. For Eg. we will use below code for snapshot test:
describe('manage profile page test suite', () => {
it('snapshot test', () => {
const setRouteLeaveHook =jest.fn();
let wrapper = shallow(
<ManageProfilePage.WrappedComponent params={{id : 25, router:
setRouteLeaveHook}}/>
);
expect(wrapper).toMatchSnapshot();
})
})
This will tell enzyme to do shallow rendering (Shallow Rendering renders only that particular component and skips child components) for ManageProfilePage which is wrapped component within WithRouter.
Shallow rendering will only render one level, that's part of the specs for it.
you can use Mount which will render the whole tree, but I don't think you can limit how many levels deep it will render.
In any case, when using High Order Components I usually just export the base component as well(before wrapping it), this way I can do all my tests without the wrapper, and simply pass mocks for the required providers.
same thing with a Connect
component with redux, you export your regular component and test the different props on that, instead of the connected one.
also note that some with...
wrappers do not expose the inner instance(some do, but some don't) , so testing on your own component instead of the wrapper helps there as well.