How can I mock Webpack's require.context in Jest?

前端 未结 8 788
执念已碎
执念已碎 2020-12-08 09:38

Suppose I have the following module:

var modulesReq = require.context(\'.\', false, /\\.js$/);
modulesReq.keys().forEach(function(module) {
  modulesReq(modu         


        
相关标签:
8条回答
  • 2020-12-08 10:30

    After spending some hours trying each of the answers above. I would like to contribute.

    Adding babel-plugin-transform-require-context plugin to .babelrc for test env fixed all the issues.

    Install - babel-plugin-transform-require-context here https://www.npmjs.com/package/babel-plugin-transform-require-context (available with yarn too)

    Now add plugin to .babelrc

    {
      "env": {
        "test": {
          "plugins": ["transform-require-context"]
        }
      }
    }
    

    It will simply transform require-context for test env into dummy fn calls so that code can run safely.

    0 讨论(0)
  • 2020-12-08 10:34

    Implementation problems not mentioned:

    1. Jest prevents out-of-scope variables in mock, like __dirname.
    2. Create React App limits Babel and Jest customization. You need to use src/setupTests.js which is run before every test.
    3. fs is not supported in the browser. You will need something like browserFS. Now your app has file system support, just for dev.
    4. Potential race condition. Export after this import. One of your require.context imports includes that export. I'm sure require takes care of this, but now we are adding a lot of fs work on top of it.
    5. Type checking.

    Either #4 or #5 created undefined errors. Type out the imports, no more errors. No more concerns about what can or can't be imported and where.

    Motivation for all this? Extensibility. Keeping future modifications limited to one new file. Publishing separate modules is a better approach.

    If there's an easier way to import, node would do it. Also this smacks of premature optimization. You end up scrapping everything anyways because you're now using an industry leading platform or utility.

    0 讨论(0)
提交回复
热议问题