【问题标题】:How to use babel-plugin-rewire with React?如何在 React 中使用 babel-plugin-rewire?
【发布时间】:2018-08-27 12:37:24
【问题描述】:

我看到了这个错误:

 ✖ 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

我的测试是这样的:

  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)
  })

我的生产代码如下所示:

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 () { ... }
}

我做错了什么?我希望断言在安装组件 Header 时调用了 profileAction()。

【问题讨论】:

    标签: reactjs ecmascript-6 jestjs babel-plugin react-test-renderer


    【解决方案1】:

    问题是 webpack 配置错误,我现在有了这个,它可以工作了:

    { 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' ], } },

    我在 webpack/loaders.js 中添加了{ query: { plugins: [ 'babel-plugin-rewire' ] } },它可以工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 2021-07-31
      • 1970-01-01
      • 2016-05-27
      • 2019-10-29
      • 2020-08-30
      相关资源
      最近更新 更多