Create-React-App instantiated from create-react-app and ejected) for the purposes of advanced testing configuration.
Namely, require.context
which is provided as a webpack function is not recognized by jest and thus requires a workaround. As this is a common issue there are several Babel plugins available to resolve this issue (see below). The goal of this exercise was to provide a quick blueprint for how to set up this plugin from extant ejected CRA configuration.
I elected to go with babel-plugin-require-context-hook which required these additional setup steps:
Install package
npm i babel-plugin-require-context-hook
Modify config\jest\babelTransform.js
module.exports = babelJest.createTransformer({
...
babelrc: true,
...
});
Create .babelrc
{
"env": {
"test": {
"plugins": ["require-context-hook"]
}
}
}
In package.json, remove any extant babel config as duplicate (copy values to .babelrc
to consolidate into one config)
In src/setupTests.js
, add registration instantiation:
import registerRequireContextHook from 'babel-plugin-require-context-hook/register';
registerRequireContextHook();
babel-plugin-transform-require-context
require.context
to replace when functionality is not neededrequire.context
call for custom global requireContext
call that checks availability of webpack function before providing a backup/mock(?) callreact-scripts
to custom-add scripts without the need to maintain all aspects of configuration long-term