[英]Jest - Test an ES6 class
I'm learning to test my JavaScript with Jest .我正在学习用Jest测试我的 JavaScript。 I have a basic project that's setup like this:我有一个基本项目,设置如下:
/
/src
myClass.js
/tests
myClass.test.js
package.json
The code looks like this:代码如下所示:
myClass.js我的类.js
export class MyClass {
constructor() {
this.result = null;
}
calculate() {
this.result = 1;
return this.result;
}
}
myClass.test.js myClass.test.js
import { MyClass } from '../src/myClass';
test('Calculate', () => {
let myObject = new MyClass();
let result = myObject.calculate();
expect(result).toBe(1);
});
package.json包.json
{
"name": "sample-project",
"version": "0.0.1",
"type":"module",
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview",
"test": "jest"
},
"dependencies": {
"vue": "^3.2.16",
"vue-router": "^4.0.11"
},
"devDependencies": {
"@vitejs/plugin-vue": "^1.9.3",
"jest": "^27.3.1",
"vite": "^2.6.4",
"vite-plugin-html": "^2.1.1",
"vite-plugin-singlefile": "^0.5.1"
}
}
When I run my tests using npm run test
, which just executes jest
, I receive an error that says: SyntaxError: Cannot use import statement outside a module
.当我使用npm run test
运行我的测试时, npm run test
执行jest
,我收到一个错误消息: SyntaxError: Cannot use import statement outside a module
。
What am I doing wrong?我究竟做错了什么? How do I test MyClass
from Jest?如何从 Jest 测试MyClass
?
Please follow the Babel
sections in the Jest's Getting Started Guide请遵循Jest 入门指南中的Babel
部分
Simply run:只需运行:
yarn add --dev babel-jest @babel/core @babel/preset-env
and create a babel.config.js
file in the project root directory with the following content:并在项目根目录下创建babel.config.js
文件,内容如下:
// babel.config.js
module.exports = {
presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};
FYI: Jest is using virtual Node environments under the hood.仅供参考:Jest 在后台使用虚拟节点环境。 If remember correctly the oldest supported Node version is 10. Therefore you need to configure a source code transformer like Babel if you want to use ES6 features.如果没记错的话,最早支持的 Node 版本是 10。因此,如果你想使用 ES6 特性,你需要配置一个像 Babel 这样的源代码转换器。 ( Source ) ( 来源)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.