简体   繁体   English

将玩笑与带有 glob 导入的文件一起使用

[英]Using jest with files with glob imports

I utilize webpack with webpack-import-glob-loader to import files using glob pattern .我使用 webpack 和webpack-import-glob-loader来使用glob pattern导入文件。 So in one of my files ( src/store/resources/module.ts ) I have a line:所以在我的一个文件( src/store/resources/module.ts )中有一行:

import '../../modules/resources/providers/**/*.resource.ts';

When I run a test with ts-jest it fails and reports the following message:当我使用ts-jest运行测试时,它失败并报告以下消息:

Cannot find module '../../modules/resources/providers/**/*.resource.ts' from 'src/store/resources/module.ts`无法从“src/store/resources/module.ts”中找到模块“../../modules/resources/providers/**/*.resource.ts”

I assume it complains because it can't recognize this import syntax.我假设它抱怨是因为它无法识别这种导入语法。

How to make jest work for project with glob imports?如何让 jest 为具有 glob 导入的项目工作?

I solved this by manually handling the globs inside of a jest preprocessor.我通过在 jest 预处理器中手动处理 glob 解决了这个问题。 Since you need to control processing of the files to handle globs in this approach, you have to manually initialize your processor.由于您需要控制文件的处理以在这种方法中处理 glob,因此您必须手动初始化处理器。

// config.js
module.exports = {
  transform: {
    '.': `./path/to/your/processor.js`

// processor.js
const path = require(`path`);
const glob = require(`glob`).sync;
const yourProcessor = // require your processor code - ts-jest, babel-jest, esbuild-jest, etc

module.exports = {
  process(src, filename, config, opts) {
    const dir = path.dirname(filename);
    src = processGlob(src, dir);
    return yourProcessor(src, filename, config, opts);
  },
};

function processGlob(src, dir) {
  // This will match things like
  //   import './**/*';
  //   import '../../modules/resources/providers/**/*.resource.ts';
  // Takes inspiration from https://github.com/excid3/esbuild-rails/blob/main/src/index.js
  return src.replace(/^import\s'(.*\*.*)';$/m, (_match, pathCapture) => {
    const matcher = /.+\..+/; // Handles '.' results
    const files = glob(pathCapture, {
      cwd: dir,
    })
      .sort()
      .filter((path) => matcher.test(path));

    return `${files.map((module, index) => `import * as module${index} from '${module}'`).join(`;`)}`;
  });
}

In this approach you can only glob once per file (because it uses the .map indexes to add numbers to each import module name).在这种方法中,每个文件只能 glob 一次(因为它使用.map索引为每个导入模块名称添加数字)。 You could keep track of a global count variable instead, if you wanted to have several glob imports in one file.如果你想在一个文件中有多个 glob 导入,你可以跟踪一个全局计数变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM