Cannot setup `babel-plugin-rewire` for React tests

拥有回忆 提交于 2019-12-29 07:55:26

问题


I'm trying to setup babel-plugin-rewire so that in my Jest tests I can generate a small test snapshot for a wrapper component instead of having a huge one with all the child components in it.

The settings seem all to be correct but I get the following error:

ReferenceError: Wrapper is not defined
  at _get_original__ (app\components\Wrapper\tests\index.te
st.js:22:2168)
  at _get__ (app\components\Wrapper\tests\index.test.js:22:
1912)
  at Suite.<anonymous> (app\components\Wrapper\tests\index.
test.js:8:82)
  at Object.<anonymous> (app\components\Wrapper\tests\index
.test.js:6:1)
  at process._tickCallback (internal\process\next_tick.js:103:7)

package.json

"babel": {
    "presets": [
      [
        "latest",
        {
          "es2015": {
            "modules": false
          }
        }
      ],
      "react"
    ],
    "env": {
      "test": {
        "plugins": [
          "babel-plugin-rewire",
          "transform-es2015-modules-commonjs",
          "dynamic-import-node"
        ]

   ...

  "devDependencies": {
    ...
    "babel-plugin-rewire": "^1.1.0",

webpack.base.babel.js

(common webpack configuration -same in webpack.basetest.babel.js)

module: {
    loaders: [{
      test: /\.js$/, // Transform all .js files required somewhere with Babel
      loader: 'babel-loader?plugins=babel-plugin-rewire',
      exclude: /node_modules/,
      query: options.babelQuery,
    },

My Test

for the Wrapper component that contains a Header child component:

import React from 'react';
import { shallow } from 'enzyme';

import Wrapper from '../index';

describe('<Wrapper />', () => {

  console.log('Debugging >>> ' + JSON.stringify(Wrapper)); // Wrapper is defined but blows up here @@

  // beforeEach(() => {
  //   Wrapper.__Rewire__('Header', class extends React.Component {
  //     render(){ return <div {...this.props}>TEST only the wrapper!!</div> }
  //   });
  // })

  // it('renders correctly', () => {
  //   const tree = shallow( <Wrapper myProps={testData.myProps} /> );
  //   expect(tree.html()).toMatchSnapshot();
  // });

  ...
});

Thanks

UPDATE: If I comment out in Wrapper the JSX where Header is used (even leaving the import for Header as it is) Wrapper.__Rewire__ becomes defined and therefore the beforeEach doesn't throw errors anymore.

来源:https://stackoverflow.com/questions/45305948/cannot-setup-babel-plugin-rewire-for-react-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!