我试图了解如何在我的 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)
关于javascript - 为什么 Jest 在 node-fetch 上失败,在导入时给出语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71401671/