question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

require.context doesn't work in tests

See original GitHub issue

I sometimes use webpack’s require.context to automatically load files from the filesystem. Example:

Directory structure:

- components
  - Button.js
  - Icon.js
  - index.js
- docs.js

index.js:

// `require` in every file except index.js from the current directory, then
// add their default export to module.exports based on their filename.
// eg module.exports["Button"] = require("./Button.js");
const req = require.context(".", false, /^\.\/(?!index).*\.js$/);
req.keys().forEach((fileName) => {
  const exportName = fileName.replace("./", "").replace(".js", "");
  module.exports[exportName] = req(fileName).default;
});

docs.js:

import * as components from "./components";
Object.entries(components).forEach(([componentName, ComponentClass]) => {
  /* generate docs for `componentName` using `ComponentClass` */
});

This example is somewhat contrived because index.js could just be replaced with:

import Button from "./Button";
import Icon from "./Icon";

export { Button, Icon }

but when you’re importing hundreds of files, this is both helpful and powerful; it’s easy to write a require.context that treats named exports differently, for example:

const req = require.context(".", false, /^\.\/(?!index).*\.js$/);
req.keys().forEach((fileName) => {
  const exportName = fileName.replace("./", "").replace(".js", "");
  // next line changed, now we export both the default export and the named docExamples export
  module.exports[exportName] = [req(fileName).default, req(fileName).docExamples];
});

This pattern allows you to co-locate documentation examples with your code, which discourages documentation getting out of sync with the component.

Although this example only addresses documentation, this pattern can be useful anywhere you have a lot of files with correlated features and enforcing an export signature convention is feasible and discourages code rot.


This is all possible using create-react-app today. However, it all breaks when you try to run your tests (in 0.3.0-alpha), because jest (naturally) doesn’t use webpack:

Using Jest CLI v14.1.0, jasmine2
 FAIL  src/__tests__/some-test.js (0s)
 Runtime Error
  - TypeError: require.context is not a function

Is require.context “too obscure” of a webpack feature? Should create-react-app start disallowing it or warning about its usage? Where and how do we draw the line on which webpack features should be supported and which should not be? Or, should we try to support require.context in the test runner enrivonment? If so, where and how do we draw the line on which webpack features should be supported in the test environment?

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:4
  • Comments:24 (11 by maintainers)

github_iconTop GitHub Comments

2reactions
cpojercommented, Aug 30, 2016

Inside of tests this is fine, you can require dynamic modules as much as you’d like and sometimes that is useful.

Outside of tests it is bad because those cases cannot be statically analyzed.

1reaction
daedalus28commented, Oct 25, 2017

FYI for anyone who encounters this issue - instead of relying on require.context or manually building a file like @gaearon suggested, you can use directory-metagen automatically generate import/requires for files in a directory. It can output es6 modules, AMD, commonjs, and more. It even has a CLI 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

How can I mock Webpack's require.context in Jest?
You don't need to install it. It will work just by adding the require('fs') directly since your Jest tests run in a NodeJS...
Read more >
How to resolve “TypeError: require.context is not a function” in ...
While we were writing Jest tests, we ran into an the error “TypeError: require.context is not a function”. This is because of the...
Read more >
Replacement for `require.context` when running Jest-Vue.js
If someone still run into this issue, you need to know that require.context is a webpack-specific feature, so it doesn't work in jest....
Read more >
Dependency Management - webpack
A context is created if your request contains expressions, so the exact module is not known on compile time. Example, given we have...
Read more >
Jest and `require.context` - Get Help - Vue Forum
... when I run a test that imports a component which includes require.context. I get an error: “TypeError: require.context is not a functi…...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found