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

标签 javascript node.js jestjs node-fetch

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

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

Jest error

我也在使用 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)

关于javascript - 为什么 Jest 在 node-fetch 上失败,在导入时给出语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71401671/

相关文章:

jestjs - 如何在 svelte 中模拟/模拟子组件事件以进行 Jest 测试?

React-Native + enzyme + Jest : How to test platform specific behaviour?

javascript - RemoveEventListener 在 Firefox 版本 58 中不起作用

javascript - 如果可以评估它并防止异常,如何安全地使用 eval() javascript 来获得指示?

javascript - D3 制作新的、更小的 CSV 文件

node.js - 通过添加从另一个请求返回的身份验证 token 来修改 http 代理请求

node.js - 如何使用 Nginx 和 Express 应用程序解决 504 网关超时和 WebSockets 错误

node.js - 为什么 Node.js crypto.sign 函数是不确定的?

javascript - 编写单元测试用例时箭头函数和普通函数有什么区别?

javascript - event.stopPropagation 无法停止向父级冒泡