我有以下行在浏览器中正确执行eval(Babel.transform(template, { presets: ['react'] }).code);
但是当我运行 Jest 测试时,我得到了 ReferenceError: React is not defined
我错过了什么?
更多信息:
在测试文件中,我有以下内容:
const wrapper = shallow(<MyComponent/>);
const instance = wrapper.instance();
instance.componentFunction(...)
然后 componentFunction 有
eval(Babel.transform(template, { presets: ['react'] }).code);
线在哪里template
它是从测试文件中获取的,可以是类似 <span>...</span>
的内容。如果需要更多详细信息,请告诉我
最佳答案
如果您在 jest 测试文件中使用 JSX,则需要将以下导入行添加到文件顶部:
import React from 'react';
这样做的原因是 Babel 将 JSX 语法转换成了一系列
React.createElement()
调用,如果你导入 React 失败,这些都会失败。
关于reactjs - 引用错误 : React is not defined in jest tests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58980934/