如何在没有Browserify的情况下测试React组件

How to test React component without Browserify

本文关键字:情况下 测试 React 组件 Browserify      更新时间:2023-09-26

我有一个react应用程序,它不使用browserfy工具。这意味着React变量由<head>中调用的react js lib的脚本导出。

// React variable is already available
var MyComponent = React.createClass({}); 

在实现了这个组件之后,我想为它创建一个测试。我查看了Jest文档,并创建了组件测试。

/** @jsx React.DOM */
jest.dontMock('../compiled_jsx/components/my-component.js');
describe('MyComponent', function() {
it('The variables are being passed to component', function() {
  var React = require('react/addons');
  // In the `MyComponent` import I got the error below: 
  // ReferenceError: /compiled_jsx/components/my-component.js: React is not defined
  var myComponent = require('../compiled_jsx/components/my-component.js'); 
});

在Jest文档示例中,组件及其测试都使用require函数来获取React变量。

有什么方法可以将React变量公开到组件中吗?或者有必要使用browserfy来创建这个测试?

Jest在node.js中运行,因此需要使用commonjs模块。你不能把浏览和玩笑混为一谈。如果你真的反对commonjs模块,你可以假设每个文件都封装在一个iffe中。

var React = typeof require === 'undefined' 
              ? window.React 
              : require('react/addons');

或者,作为测试的第一行,尝试:

global.React = require('react/addons');

无论哪种方式,导出您的组件使用:

try { module.exports = Foo; } catch (e) { window.Foo = Foo };

就我个人而言,如果你不使用commonjs模块,我认为jest是不实用的。