javascript - 为什么 Jest 在 node-fetch 上失败,在导入时给出语法错误

我试图了解如何在我的 NodeJS 单元测试中使用 Jest 修复以下错误。

使用此命令运行测试 "test": "NODE_ENV=test jest spec/* -i --coverage --passWithNoTests",

我也在使用 babel,这是我的配置

{
  "presets": [["@babel/env", { "targets": { "node": "current" } }]],
  "plugins": [
    "@babel/plugin-syntax-dynamic-import",
    ["babel-plugin-inline-import", { "extensions": [".gql"] }],
    ["@babel/plugin-proposal-decorators", { "legacy": true }]
  ]
}

在 package.json 我有这个

"jest": {
    "verbose": true,
    "collectCoverageFrom": [
      "spec/**/*.js"
    ]
  },

我在网上尝试了几个指南,但找不到解决这个问题的方法

最佳答案

您已成功配置 Jest 以转换您的 代码,但它并未转换您正在导入的模块——在本例中为 node-fetch,它具有import 源代码中的关键字(如您的错误所示)。这是因为,默认情况下,Jest 配置为 not to transform files in node_modules :

transformIgnorePatterns [array]

Default: ["/node_modules/", "\.pnp\.[^\/]+$"]

An array of regexp pattern strings that are matched against all source file paths before transformation. If the file path matches any of the patterns, it will not be transformed.

您可以设置 transformIgnorePatterns 以使用 jest.config.js 排除 node_modules 中的某些包,如下所示:

const esModules = [
  'node-fetch',
  'data-uri-to-buffer',
  'fetch-blob',
  'formdata-polyfill',
].join('|');

module.exports = {
  transformIgnorePatterns: [
    `/node_modules/(?!${esModules})`,
    '\\.pnp\\.[^\\/]+$',
  ],
};

(参见 https://github.com/nrwl/nx/issues/812#issuecomment-429420861)

https://stackoverflow.com/questions/71401671/

相关文章:

c# - 检测持续时间值列表中的闪烁

css - 如何简化这些 CSS 选择器?

sql - 如何在 Snowflake 中嵌套使用一个流的存储过程?

python-3.x - SSHTunnel 搜索默认私钥 (id_rsa) 而不是我指定的 ssh

nestjs - 导出 NestJs 模块与导出提供程序

telegram - 热门从 Telegram Bot 消息中获取回调数据

typescript - 如何使用带有更新的 FirestoreDataConverter?

swift - AVPlayer 在 iOS 15.4 中寻求 completionHandler

reactjs - 使用 useEffect 监听子组件可以吗?

machine-learning - 如何使用 mlflow REST api 记录模型? mlfl