Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest/React - How to use global object in unit tests?

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
});

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.)

like image 617
Csati Avatar asked May 14 '15 09:05

Csati


People also ask

How do you mock global objects in Jest?

When mocking global object methods in Jest, the optimal way to do so is using the jest. spyOn() method. It takes the object and name of the method you want to mock, and returns a mock function. The resulting mock function can then be chained to a mocked implementation or a mocked return value.

How does Jest tests within a DOM environment?

How does Jest test within a DOM environment? Jest ships with jsdom, which simulates a DOM environment as if you were in a browser. This means that every DOM API that we call can be observed in the same way it would be observed in a browser.

Which is better Enzyme or Jest?

Shallow rendering is one way that Enzyme keeps tests simpler than Jest. When you shallow-render a component with Enzyme, you render only that component. Enzyme doesn't render any of the children of that component. This is a useful restriction that ensures that you aren't testing too much in one test.


1 Answers

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
like image 173
Csati Avatar answered Nov 12 '22 20:11

Csati