Suppose I have the following module:
var modulesReq = require.context('.', false, /\.js$/);
modulesReq.keys().forEach(function(module) {
modulesReq(module);
});
Jest complains because it doesn't know about require.context
:
FAIL /foo/bar.spec.js (0s)
● Runtime Error
- TypeError: require.context is not a function
How can I mock it? I tried using setupTestFrameworkScriptFile
Jest configuration but the tests can't see any changes that I've made in require
.
Installing
package and adding the plugin in the .babelrc resolved the issue for me. Refer to the documentation here: https://www.npmjs.com/package/babel-plugin-transform-require-context
I had the same problem, then I've made a 'solution'.
I'm pretty sure that this is not the best choice. I ended up stopping using it, by the points answered here:
https://github.com/facebookincubator/create-react-app/issues/517 https://github.com/facebook/jest/issues/2298
But if you really need it, you should include the polyfill below in every file that you call it (not on the tests file itself, because the
require
will be no global overridden in a Node environment).With this function, you don't need to change any
require.context
call, it will execute with the same behavior as it would (if it's on webpack it will just use the original implementation, and if it's inside Jest execution, with the polyfill function).Simpleset Solution for this
Just Do
}
So Here I have added extra check if require.context is defined then only execute By Doing this jest will no longer complain
If you are using Babel, look at babel-plugin-require-context-hook. Configuration instructions for Storybook are available at Storyshots | Configure Jest to work with Webpack's require.context(), but they are not Storyshots/Storybook specific.
To summarise:
Install the plugin.
Create a file
.jest/register-context.js
with the following contents:Configure Jest (the file depends on where you are storing your Jest configuration, e.g.
package.json
):Add the plugin to
.babelrc
Alternatively, add it to
babel.config.js
:It may be worth noting that using
babel.config.js
rather than.babelrc
may cause issues. For example, I found that when I defined therequire-context-hook
plugin inbabel.config.js
:jest --coverage
didn't pick it up (perhaps Istanbul isn't up to speed with Babel 7?).In all cases, a
.babelrc
configuration was fine.Remarks on Edmundo Rodrigues's answer
This
babel-plugin-require-context-hook
plugin uses code that is similar to Edmundo Rodrigues's answer here. Props to Edmundo! Because the plugin is implemented as a Babel plugin, it avoids static analysis issues. e.g. With Edmundo's solution, Webpack warns:Despite the warnings, Edmundo's solution is the most robust because it doesn't depend on Babel.
Extract the call to a separate module:
Use the new module in the module where you extracted it from:
Create a mock for the newly created bundle-loader module:
Use the mock in your test: