Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'match' property not set on props when using MemoryRouter in test

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.

like image 528
Mike Bamford Avatar asked Mar 08 '23 02:03

Mike Bamford


1 Answers

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.

like image 167
Pierre Kraemer Avatar answered Apr 09 '23 15:04

Pierre Kraemer