2

I have a react application that doesn't uses the browserify tool. It means that the React variable is exported by the script of the react js lib called in the <head>.

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

After implementing this component, I want to create a test for it. I took a look at Jest documentation and I've created my component test.

/** @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'); 
});

In the Jest documentation example, both component and its tests uses the require function for getting the React variable.

Is there any way to expose React variable into the component? Or it's necessary using browserify for creating this test?

Helielson Santos
  • 231
  • 1
  • 2
  • 10

1 Answers1

2

Jest runs in node.js, so you need to use commonjs modules. You don't use browserify with jest. If you're really against commonjs modules you can do this assuming each file is wrapped in an iffe.

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

Or alternatively as the first line of your tests, try:

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

And either way, export your components using:

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

Personally, I don't think jest is practical if you're not using commonjs modules.

Brigand
  • 84,529
  • 20
  • 165
  • 173
  • I'm not using commonjs modules, but I'm using React and I didn't find a better way for testing my React application than Jest. I've thought about putting a `try/catch` treatment, but it seems ugly to me. I'm looking for a better way for doing it. Which test lib do you recommend instead of Jest? Thanks in advance. – Helielson Santos Sep 23 '14 at 06:09
  • Jest is the best option, but mocha + react's test-utils should be good enough. You'll either need to use karma + phantomjs, or a browser based test runner (I think mocha has one). – Brigand Sep 23 '14 at 08:50
  • 1
    Alright. I think it's better adapting my application for using commonjs modules . Thanks @FakeRainBrigand – Helielson Santos Sep 23 '14 at 17:58