mercredi 28 juin 2017

Testing mounted components with react-router v4

I'm migrating our application to react-router@4.x, and I'm having troubles with getting the tests that are using enzyme's mount function.

Whenever I mount a component that has a withRouter-wrapped sub-component, I run into trouble.

Here's an example of a simplified situation of what I'm testing:

class SomePage extends React.Component {
  componentDidMount() {
    this.props.getData();
  }
  render() {
    return (
      <div>
        <ComponentWrappedInWithRouter />
      </div>
    );
  }
}

const Component = (props) => (
  <button onClick={() => this.props.history.push('/new-route') }>
    Click to navigate
  </button>
);

const ComponentWrappedInWithRouter = withRouter(Component);

Now, I want to test that SomePage calls its prop getData after it's mounted. Stupid example, I know, but the structure should be sufficient.

Whenever I write a test that uses enzyme's mount, I get the following error:

TypeError: Cannot read property 'route' of undefined
  at Route.computeMatch (node_modules/react-router/Route.js:68:22)
  at new Route (node_modules/react-router/Route.js:47:20)

Now, I think the reason this happens is because I try to call withRouter for a component that does not have router on the context - i.e. it has not been wrapped in <BrowserRouter /> or one of its siblings.

I can fix this by wrapping my component in a <BrowserRouter /> at test time, but that isn't a very nice fix.

This wasn't an issue with react-router@3.x, but since the current major was a full rewrite, I totally understand that these issues will arise.

Any ideas as to how I can fix this?

Aucun commentaire:

Enregistrer un commentaire