如何在Jest中模拟Webpack的require.context? [英] How can I mock Webpack's require.context in Jest?

查看:1141
本文介绍了如何在Jest中模拟Webpack的require.context?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下模块:

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

Jest抱怨是因为它不了解require.context:

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

我该如何嘲笑它?我尝试使用 setupTestFrameworkScriptFile Jest配置,但测试看不到任何更改我在require中制作的.

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.

推荐答案

我遇到了同样的问题,然后我提出了解决方案".

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/问题/517 https://github.com/facebook/jest/issues/2298

但是,如果您确实需要它,则应在调用它的每个文件中包括以下polyfill(而不是在测试文件本身中,因为require在Node环境中不会被全局覆盖).

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).

// This condition actually should detect if it's an Node environment
if (typeof require.context === 'undefined') {
  const fs = require('fs');
  const path = require('path');

  require.context = (base = '.', scanSubDirectories = false, regularExpression = /\.js$/) => {
    const files = {};

    function readDirectory(directory) {
      fs.readdirSync(directory).forEach((file) => {
        const fullPath = path.resolve(directory, file);

        if (fs.statSync(fullPath).isDirectory()) {
          if (scanSubDirectories) readDirectory(fullPath);

          return;
        }

        if (!regularExpression.test(fullPath)) return;

        files[fullPath] = true;
      });
    }

    readDirectory(path.resolve(__dirname, base));

    function Module(file) {
      return require(file);
    }

    Module.keys = () => Object.keys(files);

    return Module;
  };
}

使用此功能,您无需更改任何require.context调用,它将以与原来相同的行为执行(如果在webpack上,它将仅使用原始实现,并且如果在Jest执行内部,带有polyfill功能).

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).

这篇关于如何在Jest中模拟Webpack的require.context?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆