我正在使用
jest:24.9.0
,无需任何配置,从 create-react-app 全局安装。在这些文件中我使用 es6 模块。使用时没有报错"test": "react-scripts test"
但是,当我将
jest
与 "test": "jest --config jest.config.js",
一起使用时,我看到以下错误。
FAIL src/configuration/notifications.test.js
● Test suite failed to run
/var/www/management/node/src/configuration/notifications.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import notifications from './notifications';
^^^^^^
SyntaxError: Cannot use import statement outside a module
Jest 不支持
ES6
模块,因此当您直接使用 Jest 运行测试时会抛出此错误。如果你想这样运行那么你必须添加 babel。
另一方面,当您使用
react-scripts
运行测试时,它会在幕后使用 babel 来转译代码。
在新版本的 jest 中,
现在由 Jest 自动加载并完全集成babel-jest
希望这能回答您的问题。
开玩笑地添加 babel。
安装
babel-jest
现在由 Jest 自动加载并完全集成。仅当您使用 babel-jest 转换 TypeScript 文件时才需要执行此步骤。
npm install --save-dev babel-jest
用法
在您的
package.json
文件中进行以下更改:
{
"scripts": {
"test": "jest"
},
"jest": {
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
}
}
}
创建
.babelrc
配置文件
在项目根目录中创建一个
babel.config.json
配置并启用一些 presets
。
首先,您可以使用 env 预设,它支持 ES2015+ 的转换
npm install @babel/preset-env --save-dev
为了启用预设,您必须在
babel.config.json
文件中定义它,如下所示:
{
"presets": ["@babel/preset-env"]
}
了解更多详情
正如上面的答案所描述的,Jest 不支持 ES6 模块。因此,我们需要将代码转换为支持的模块类型。我们可以使用
babel-jest
或 ts-jest
。为了简单起见,我建议使用 ts-jest
。
第1步:安装:
npm i -D ts-jest @types/jest
或 yarn add --dev ts-jest @types/jest
第2步:配置
选项 1:创建 jest 配置文件
jest.config.js
module.exports = {
transform: {
'^.+\\.(ts|tsx)$': 'ts-jest',
},
};
选项 2:将 jest 配置添加到
package.json
"jest": {
"transform": {
"^.+\\.(ts|tsx)$": "ts-jest"
}
}
第 3 步:执行脚本。 现在一切都应该已设置完毕。
由于 jest 不能很好地与 esmodules 配合使用,因此您需要在
jest.config.js
中添加这些配置,以告诉 Jest 使用 commonJS 构建来代替
moduleNameMapper : {
'^react-dnd$': 'react-dnd/dist/cjs',
'^react-dnd-html5-backend$': 'react-dnd-html5-backend/dist/cjs',
'^dnd-core$': 'dnd-core/dist/cjs',
}
错误
SyntaxError: Cannot use import statement outside a module
也可能来自
node_modules
下的某些导入库,例如
...\node_modules\node-fetch\src\index.js:9
import http from 'node:http';
^^^^^^
对我来说,技巧是使用 jest 配置中的
transformIgnorePatterns
选项:
transformIgnorePatterns: [
'node_modules/(?!' +
[
'node-fetch',
'fetch-blob',
'data-uri-to-buffer',
'jest-runtime',
'formdata-polyfill'
].join('|') +
')',
],
另请参阅
我使用反应脚本运行测试时收到了同样的错误。我能够通过更改 package.json 中的行来解决这个问题
"test": "react-scripts test",
到
"test": "NODE_OPTIONS=--experimental-vm-modules react-scripts test",
从提供建议此解决方案的链接的错误消息中:
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
我想补充一下我是如何轻易地为自己造成这个问题的。我吓坏了,通过在我的 .gitignore 中包含所有 *.js 来阻止自己提交我的 jest.config.js 文件。每次我的 CI 运行时,我都会收到此错误,因为我的存储库中没有版本控制的 jest.config.js 。各位出门在外要小心!保持冷漠。
这个问题在源码包中进行了很长的讨论,并提供了一些替代解决方案https://github.com/kulshekhar/ts-jest/issues/1174.
对我有用的解决方案,使用
Typescript
、ES6
模块和 jest
是使用包 ts-jest-mock-import-meta