How to resolve “TypeError: require.context is not a function” in Jest

In Handoff, we use Webpack’s require.context function, to dynamically load JavaScript files.

While we were writing Jest tests, we ran into an the error “TypeError: require.context is not a function”. This is because of the fact the that the JS files are not bundled by Webpack, but by Jest.

If you use Babel, there is simple workaround that can be done as follows:

npm i -D babel-plugin-transform-require-context

then update your .babelrc or babel.config.js as follows:

this could also be named .babelrc

Simply run your tests now and it should be good to go!

Note: the Babel transform plugin will change the return value of the require.contextcall so that it will not resolve to anything. This means that if you need the actual code to be lifted from disk, this will not work (!).

--

--