How to test react-router with enzyme

2019-01-23 13:55发布

I am using enzyme+mocha+chai to test my react-redux project. Enzyme provides shallow to test component behavior. But I didn't find a way to test the router. I am using react-router as below:

<Router history={browserHistory}>
     ...
        <Route path="nurse/authorization" component{NurseAuthorization}/>
     ...
  </Route>

I want to test this route nurse/authorization refer to NurseAuthorization component. How to test it in reactjs project?

EDIT1

I am using react-router as the router framework.

2条回答
疯言疯语
2楼-- · 2019-01-23 14:37

You can wrap your router inside a component in order to test it.

Routes.jsx

export default props => (
  <Router history={browserHistory}>
    ...
    <Route path="nurse/authorization" component{NurseAuthorization}/>
    ...
  </Route>
)

index.js

import Routes from './Routes.jsx';
...

ReactDOM.render(<Routes />, document.getElementById('root'));

Then you have to shallow render your Routes component, and you are able to create an object map to check the correspondance between path and related component.

Routes.test.js

import { shallow } from 'enzyme';
import { Route } from 'react-router';
import Routes from './Routes.jsx';
import NurseAuthorization from './NurseAuthorization.jsx';

it('renders correct routes', () => {
  const wrapper = shallow(<Routes />);
  const pathMap = wrapper.find(Route).reduce((pathMap, route) => {
    const routeProps = route.props();
    pathMap[routeProps.path] = routeProps.component;
    return pathMap;
  }, {});
  // { 'nurse/authorization' : NurseAuthorization, ... }

  expect(pathMap['nurse/authorization']).toBe(NurseAuthorization);
});
查看更多
欢心
3楼-- · 2019-01-23 14:39

I had my paths defined in another file for the dynamic router, so I am also testing that all the routes I am rendering as Routes are defined in my paths.js constants:

it('Routes should only have paths declared in src/routing/paths.js', () => {
  const isDeclaredInPaths = (element, index, array) => {
    return pathsDefined.indexOf(array[index]) >= 0;
  }
  expect(routesDefined.every(isDeclaredInPaths)).to.be.true;
});
查看更多
登录 后发表回答