, <MemoryRouter>< *your component here* ></MemoryRouter>
. Typescript , , , .
React Router v4 .
, HOC withRouter
, withRouter
react-router
history
.
, .
<MemoryRouter>
<MemoryRouter>
, .
import { createMemoryHistory, createLocation } from 'history';
import { match } from 'react-router';
const history = createMemoryHistory();
const path = '/route/:id';
const match: match<{ id: string }> = {
isExact: false,
path,
url: path.replace(':id', '1'),
params: { id: "1" }
};
const location = createLocation(match.url);
test('shallow render', () => {
const wrapper = shallow(
<MyComponent history={history}
location={location}
match={match} />
);
expect(wrapper).toMatchSnapshot();
});
ATTENTION ! Do not use this to check implementation details, it may be tempting, but it can cause you a lot of pain if you want to refactor.
Creating an assistant for this would probably be the best way to make it reusable.
import { createLocation, createMemoryHistory } from 'history';
import { match as routerMatch } from 'react-router';
type MatchParameter<Params> = { [K in keyof Params]?: string };
export const routerTestProps = <Params extends MatchParameter<Params> = {}>
(path: string, params: Params, extendMatch: Partial<routerMatch<any>> = {}) => {
const match: routerMatch<Params> = Object.assign({}, {
isExact: false,
path,
url: generateUrl(path, params),
params
}, extendMatch);
const history = createMemoryHistory();
const location = createLocation(match.url);
return { history, location, match };
};
const generateUrl = <Params extends MatchParameter<Params>>
(path: string, params: Params): string => {
let tempPath = path;
for (const param in params) {
if (params.hasOwnProperty(param)) {
const value = params[param];
tempPath = tempPath.replace(
':${param}', value as NonNullable<typeof value>
);
}
}
return tempPath;
};
Now we can just use the function routerTestProps
in our tests.
const { history, location, match } = routerTestProps('/route/:id', { id: '1' });