mardi 30 janvier 2018

Jest testing component getting "TypeError: (0 , _reactRouter.withRouter) is not a function"

This is a whopper.

I recently updated from react-router 3 to react-router 4. My single page app compiles via webpack just fine, and I can navigate my local dev version just fine in the browser.

However, tests that involve components that are wrapped with the withRouter HOC fail.

Specifically, if the component being tested has a descendant component that uses the withRouter HOC, you can't even import withRouter. A console log shows that withRouter is imported as "undefined"

The folder has the following files.

app/
├── src/
    ├── LoginContainer.jsx
    ├── LoginForm/
        ├── index.js
        └── LoginForm.jsx

LoginContainer (A react container component)

import React from 'react';
import PropTypes from 'prop-types';
import LoginForm from './LoginForm';

export default class LoginContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { currentForm: props.form };
    this.changeForm = this.changeForm.bind(this);
  }

  changeForm(form) {
    // handle when someone changes something.
  }

  render() {
    return (
      <section>
        <LoginForm {...this.props} changeForm={this.changeForm} data-form={this.state.currentForm} />
      </section>
    );
  }
}

LoginForm/index.js (basically a HOC that wraps LoginForm.jsx)

import LoginForm from './LoginForm';
import { withRouter } from 'react-router';

// NO MATTER WHAT I DO...
// withRouter is undefined.
// If I do import * as bob from 'react-router'
// bob then equals { default: {} }
// bob is blank!

export default withRouter(LoginForm);

For some reason, I can't import withRouter when testing. All other modules import just fine, only withRouter is causing issues.

  • react-router and react-router-dom are both installed as dependencies
  • Other components that use things like Link or Route pass tests just fine

Aucun commentaire:

Enregistrer un commentaire