一,前言
babel-jest不能进行语法检查
ts-jest支持语法检查
二,jest安装和配置
安装包并配置脚本:
"scripts": {
"test": "jest"
},
"devDependencies": {
"@types/jest": "^24.0.15",
"jest": "^24.8.0",
"ts-jest": "^24.0.2",
},
生成jest配置文件:
npx ts-jest config:init
jest.config.js:
module.exports = {
preset: 'ts-jest', // preset
testEnvironment: 'node', // node环境
};
三,待测试代码
src/math.ts
function add(a: number, b: number) {
return a + b;
}
function sub(a: number, b: number) {
return a - b;
}
// 导出
module.exports = {
add,
sub
}
四,编写测试用例
src/test/math.test.ts
const math = require('../src/math');
test('add: 1 + 2 = 3', () => {
expect(math.add(1, 2)).toBe(3);
});
test('sub: 1 - 2 = -1', () => {
expect(math.sub(1, 2)).toBe(-1);
});
四,执行测试用例
npm run test