12

我正在使用 webpack-provide-plugin 导入反应。

new webpack.ProvidePlugin({
        "React": "react",
}),

// text.jsx

let text = (props) => (
  <div> 
    <p class="text">this.props.text</p>
  </div>
)

export default text 

//text.test.js

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

it('Renders text', () => {
    const wrapper = shallow(<text/>);
    expect(wrapper.hasClass("text")).toEqual(true);
});

但是在用 jest 运行 react 组件测试时,我得到了错误

ReferenceError: React is not defined

当然,因为 react 没有明确导入。除了显式导入和放弃提供插件之外,还有其他方法可以解决这个问题吗?

4

2 回答 2

24

您可以像这样为 Jest 创建一个设置文件:

//jest.setup.js
window.React = require('react');

并将其添加到 Jest config: "setupFiles": [ "<rootDir>/jest.setup.js" ], http://facebook.github.io/jest/docs/configuration.html#setupfiles-array

于 2017-01-04T22:14:29.407 回答
0

当您使用 webpack 提供插件证明此变量时,删除此行;

从“反应”导入反应;

于 2018-02-08T08:13:16.597 回答