如何让jest能够与ES6依赖项一起工作

5

我将一个依赖包拉入我的node_modules文件夹中。这个包含有一个导出,像这样:

        ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './client';

为了解决这个问题,我使用了https://github.com/standard-things/esm。在我的node加载器中使用:node -r esm index.js。但是,这对于使用Jest的测试不起作用。我似乎无法弄清楚如何让Jest为我转换这些导入。我尝试了很多方法,但目前配置文件的状态如下:
// babel.config.js
// babel.config.js
module.exports = {
    presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript'],
    plugins: ['@babel/plugin-transform-modules-commonjs'],
};



const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig');

module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'node',
    testMatch: ['<rootDir>/tests/**/*.{ts,js}'],
    testPathIgnorePatterns: ['global.d.ts', 'utils.ts', '<rootDir>/node_modules/'], // tried with and without this
    moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/' }),
};

依然收到该错误。 有人有建议吗?


https://github.com/nrwl/nx/issues/812#issuecomment-429420861 - Adam Jenkins
我已经尝试过了,但仍然没有运气。 - Robert Lemiesz
1个回答

8

transformIgnorePatterns 默认值为 ["/node_modules/"],这意味着在运行 Jest 时默认情况下不会对 node_modules 中的任何内容进行转换。

如果您有一个依赖项在运行单元测试之前需要进行转换,则需要在您的 Jest 配置中使用 transformIgnorePatterns 白名单它:

"transformIgnorePatterns": [
  "node_modules/(?!(module-that-needs-to-be-transformed)/)"
]

哇,我应该更仔细地阅读我的代码。我设置的是“testPathIgnorePatterns”,而不是“transformIgnorePatterns”。谢谢,这解决了我的问题。 - Robert Lemiesz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接