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.)
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 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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With