5

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

1 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

2 Comments

I found that I had to clear the haste cache to get this to work. rm -rf node_modules/.haste_cache
The setupEnvScriptFile configuration option has been deprecated for a while. Jest 15 removes it completely and replaces it with setupFiles. This option expects an array of file paths that are loaded in order before a test file is executed. facebook.github.io/jest/blog/2016/09/01/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.