开玩笑/反应-如何在单元测试中使用全局对象? [英] Jest/React - How to use global object in unit tests?

查看:227
本文介绍了开玩笑/反应-如何在单元测试中使用全局对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于开玩笑/反应-如何在单元测试中使用全局对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆