初学jest,如何配置支持esmodule、ts
基础使用
- 安装jest
yarn add jest -D
- 配置package.json
{
"scripts": {
"test": "jest"
},
"devDependencies": {
"jest": "^27.5.1"
}
}
- 测试代码
// sum.js
module.exports = function sum(a, b) {
return a + b;
};
// sum.spec.js
const sum = require("./sum");
test("sum", () => {
expect(sum(1, 1)).toBe(2);
});
- 测试
yarn test
没有问题

文章图片
配置支持esmodule 未做任何配置,直接将导入导出改为esmodule将会出现这样的错误

文章图片
官方文档
只需要在package.json中一点配置即可支持esmodule
{
"license": "ISC",
"type": "module",
"scripts": {
"test": "NODE_OPTIONS=--experimental-vm-modules jest"
},
"devDependencies": {
"jest": "^27.5.1"
}
}
允许测试成功,不过会有一个提示说
VM Modules是一个实验特性

文章图片
配置支持ts 除了jest需要安装
@types/jest
ts-jest
typescript
这三个包yarn add ts-jest @types/jest typescript -D
- 配置文件
jest.config.js
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
};
- 配置
tsconfig.json
"test": "jest"
就行{
"compilerOptions": {
"esModuleInterop": true
}
}
- 测试代码
// sum.ts
export function sum(a, b) {
return a + b;
}// sum.spec.ts
import { sum } from "./sum";
describe("sum", () => {
it("sum: 1+1=2", () => {
expect(sum(1, 1)).toBe(2);
});
});
- 运行测试
yarn test
完美
【初学jest,如何配置支持esmodule、ts】

文章图片
推荐阅读
- 从构建到使用,openLooKeng 如何实现 Hash Join ()
- 详解如何在JavaScript中创建线性仪表图
- 如何使用DTM将App事件发送到Google|如何使用DTM将App事件发送到Google Analytics
- 如何在有限算力下实现智能驾驶多任务高精度识别()
- Mybatis如何使用正则模糊匹配多个数据
- 如何构建可重复读取inputStream的request
- SpringBoot如何接收Post请求Body里面的参数
- Java|Java初学者学习笔记(一)
- 出版|如何在nature上发表文章
- 如何通过学生邮箱(教育邮箱)申请Jetbrains系列软件无限期试用