I have been trying to get tests working for react-router v4. I have taken the documented basic example here and written the following test for it:
import React from 'react';
import { Topic } from './App';
import { MemoryRouter } from 'react-router-dom'
import TestRenderer from 'react-test-renderer';
test('it renders', () => {
TestRenderer.create(
<MemoryRouter initialEntries={['/topics/props-v-state']} initialIndex={0}>
<Topic/>
</MemoryRouter>
);
});
I get the error: "TypeError: Cannot read property 'params' of undefined" which I interpret as the match property not
being set on props of the Topic component by MemoryRouter. My dependencies are:
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-router-dom": "^4.2.2",
"react-scripts": "1.1.0"
},
"devDependencies": {
"babel-jest": "22",
"babel-preset-es2015": "6",
"babel-preset-react": "6",
"jest": "22",
"react-test-renderer": "16"
},
I guess I could just do <Topic match={{url: '/topics/props-v-state'}} /> but the documentation here
seems to imply that this can be done through MemoryRouter.
Any help greatly appreciated.
The match, history and location props are only passed to components rendered by a Route component. Other components that need access to these properties can be wrapped with a call to the withRouter HOC.
Your example could be written:
import React from 'react';
import { Topic } from './App';
import { MemoryRouter, withRouter } from 'react-router-dom';
import TestRenderer from 'react-test-renderer';
const RTopic = withRouter(Topic);
test('it renders', () => {
TestRenderer.create(
<MemoryRouter initialEntries={['/topics/props-v-state']} initialIndex={0}>
<RTopic/>
</MemoryRouter>
);
});
As an alternative, your App module could directly export a component that is wrapped by withRouter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With