Unit testing React stateless component wrapped with withRouter() in Enzyme, how to pass match parameter

Viewed 1475

I'm trying to test a React functional component that I've wrapped in withRouter from react-router-dom. The component structure is as below.

import * as React from 'react';
import { Switch, Route, withRouter, RouteComponentProps } from 'react-router-dom';


export interface Props extends RouteComponentProps {
    closeModalLinkPath: string;
    closeModalFunction: any;
}

const RouterWrappedComponent= withRouter(({ match, history, closeModalLinkPath, closeModalFunction }: Props) => {

return (<div></div)
    }
});

export default RouterWrappedComponent;

This structure works perfectly in the browser, however I am having difficulty writing unit tests. Due to the nature of the component I need an accurate match object but I can't find any way of passing this through on generation.

var routerWrappedComponent= Enzyme.mount(<MemoryRouter initialEntries={[`/studio/00000000-0000-0000-0000-000000000000/manage`]}>
    <RouterWrappedComponent closeModalFunction={() => { }} closeModalLinkPath={`/studio/00000000-0000-0000-0000-000000000000`} />
</MemoryRouter>);

Despite the component's props inheriting from RouteComponentProps I can't add this to the components props and I can't find any variation of MemoryRouter that will let me pass match in through props, can anyone help?

EDIT: The withRouter wrapping came from here

1 Answers

OK so there doesn't seem to be any way to pass match as a parameter but I've found a pretty elegant solution. The reason match is empty on the component is because it's being directly rendered, it hasn't matched with anything. I've wrapped the component in a route that matches the initialEntries prop on MemoryRouter as below.

var routerWrappedComponent= Enzyme.mount(<MemoryRouter initialEntries={[`/studio/00000000-0000-0000-0000-000000000000/manage/11111111-0000-0000-0000-000000000000`]}>
       <Route path={`/studio/:customerId/:page/:serviceId`} component={() =>  
    <RouterWrappedComponent closeModalFunction={() => { }} closeModalLinkPath={""} />
</MemoryRouter>);

and presto, match is filled

match: { path: '/studio/:customerId/:page/:serviceId',
    url: '/studio/00000000-0000-0000-0000-000000000000/manage/11111111-0000-0000-0000-000000000000',
    isExact: true,
    params:
     { customerId: '00000000-0000-0000-0000-000000000000',
       page: 'manage',
       serviceId: '11111111-0000-0000-0000-000000000000' } }
Related