我试图设置babel-plugin-rewire,以便在我的Jest测试中,我可以为包装器组件生成一个小的测试快照,而不是包含一个包含所有子组件的巨大的快照。
设置似乎都是正确的,但我收到以下错误:
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)
"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配置 - 在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,
},
包含Header子组件的Wrapper组件:
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();
// });
...
});
由于
更新
如果我在Wrapper中注释掉使用Header的JSX(即使保留了Header的导入),Wrapper.__Rewire__
也会被定义,因此beforeEach
不会再抛出错误。