做单元测试有很多的工具,今天在一个老项目中看到的用的工具是用的jest
做的单元测试,特尝试更新下,遇到不少的问题。
相关依赖配置文件
npm install --save-dev jest
- package.json
{
"name": "jest-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.26.0",
"@babel/preset-env": "^7.26.0",
"@babel/preset-typescript": "^7.26.0",
"babel-jest": "^29.7.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"ts-jest": "^29.2.5",
"ts-node": "^10.9.2",
"typescript": "^5.6.3"
},
"dependencies": {
"tslib": "^2.8.0"
}
}
- tsconfig.json
{
"compileOnSave": true,
"compilerOptions": {
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"experimentalDecorators": true,
"esModuleInterop": true,
"importHelpers": true,
"declaration": true,
"outDir": "./dist",
"sourceMap": true,
"baseUrl": "./",
"allowSyntheticDefaultImports": true,
"paths": {
"@/*": ["./src/*"],
"tslib": ["node_modules/tslib/tslib.d.js"]
},
"target": "es5",
"lib": ["DOM", "ESNext"]
},
"include": ["src/**/*"]
}
生成基础配置文件
npm init jest@latest
- jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
transform: {
'^.+\\.tsx?$': 'ts-jest',
'^.+\\.jsx?$': 'babel-jest' // 使用 babel-jest 进行转换
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
// 添加其他 Jest 配置
}
使用 Babel
要使用esm
语法,必须配置babel
,否则会报错
- babel.config.js
module.exports = {
presets: [['@babel/preset-env', { targets: { node: 'current' } }]]
}
报错:This syntax requires an imported helper but module ‘tslib‘ cannot be found
解决方案如下:
1、安装tslib
npm install tslib
2、tsconfig.json中"compilerOptions"选项下新增“baseUrl”及“paths”配置
"baseUrl":".",
"paths": {
"tslib" : ["node_modules/tslib/tslib.d.ts"]
}
- .src/index.ts
export * from './array'
- array.ts
export function sum(a: number, b: number): number {
return a + b
}
- 测试用例src/test/index.test.js,运行jest命令会自动搜索测试文件名
xxx.test.js
包含test的文件里面的内容
import { sum } from '../index'
test('adds 1 + 2 to equal 4 ', () => {
expect(sum(1, 2)).toBe(4)
})
test('adds 1 + 2 to equal 3 ', () => {
expect(sum(1, 2)).toBe(3)
})
逐个运行测试
一般都是命令行运行
附件
源码地址:https://gitee.com/motain/jest-app