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

查看:33
本文介绍了如何在 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/问题/517https://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天全站免登陆