Jest/React - 如何在单元测试中使用全局对象? [英] Jest/React - How to use global object in unit tests?
本文介绍了Jest/React - 如何在单元测试中使用全局对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用带有 require() 的 CommonJS 模块,除了 React 是全局的:
I use CommonJS modules with require() except React, which is global:
// I don't want require React in every module:
// var React = require("react");
var MyComponent = React.createClass({ // React is global here
});
在 MyComponent 上运行单元测试时,Jest 找不到 React.有没有办法告诉 Jest 插入一个全局 React 对象?(我使用 npm 和 gulp-browserify.)
When running a unit test on MyComponent, Jest can't find React. Is there a way to tell Jest to insert a global React object? (I use npm and gulp-browserify.)
推荐答案
使用以下设置对我有用.
Works for me with the following settings.
// package.json
"jest": {
"scriptPreprocessor": "preprocessor.js",
"unmockedModulePathPatterns": [
"react"
],
"setupEnvScriptFile": "before_test.js"
}
// preprocessor.js
var ReactTools = require('react-tools');
module.exports = {
process: function(src) {
return ReactTools.transform(src);
}
};
// before_test.js
React = require("react"); // Global React object
这篇关于Jest/React - 如何在单元测试中使用全局对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文