简体   繁体   中英

How to use babel-plugin-rewire with React?

I'm seeing this error:

 ✖ should dispatch profileAction
      PhantomJS 1.9.8 (Linux 0.0.0)
    TypeError: 'undefined' is not a function (evaluating '_Header2.default.__Rewire__('profileAction', function (a) {
          a();
        })')
        at     /home/piousbox/Dropbox/projects/colombia_tailors_react/app/app.tests.js:74904 <- webpack:///app/components/App/__tests__/Header-test.jsx:23:53

My test looks like this:

  it('should dispatch profileAction', (done) => {
    Header.__Rewire__('profileAction', (a) => { a() })
    let r = ReactTestUtils.renderIntoDocument(
      <Provider store={store}>
        <Header router={{location:{}}} />
      </Provider>)
    let elem = ReactDOM.findDOMNode(r)
  })

My production code looks like this:

import { profileAction } from '../../actions/profileActions'
profileAction // eslint-disable-line no-unused-expressions
class Header extends React.Component {
  constructor(props) {
    super(props)
    props.dispatch(profileAction())
  }
  render () { ... }
}

What am I doing wrong? I am looking to assert that profileAction() was called when the component Header was mounted.

The issue was misconfiguration of webpack, I now have this and it works:

{ test: /\\.jsx?$/, exclude: /node_modules/, - loader: 'babel-loader?plugins=babel-plugin-rewire', + loader: 'babel-loader', query: { - presets: [ 'babel-preset-es2015', 'babel-preset-stage-2', 'babel-preset-react' ] + presets: [ 'babel-preset-es2015', 'babel-preset-stage-2', 'babel-preset-react' ], + plugins: [ 'babel-plugin-rewire' ], } },

I added { query: { plugins: [ 'babel-plugin-rewire' ] } } to webpack/loaders.js, and it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM