Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Jest/React-如何在单元测试中使用全局对象?_Javascript_Unit Testing_Reactjs_Jestjs - Fatal编程技术网

Javascript Jest/React-如何在单元测试中使用全局对象?

Javascript Jest/React-如何在单元测试中使用全局对象?,javascript,unit-testing,reactjs,jestjs,Javascript,Unit Testing,Reactjs,Jestjs,我将CommonJS模块与require()一起使用,React除外,它是全局的: // 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对象?(我使

我将CommonJS模块与require()一起使用,React除外,它是全局的:

// 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。)

适用于以下设置

// 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

我发现我必须清除haste缓存才能让它工作
rm-rf node_modules/.haste_cache
setupEnvScriptFile配置选项已被弃用一段时间。Jest 15将其完全删除,并将其替换为setupfile。此选项要求在执行测试文件之前按顺序加载文件路径数组。