jest基础入门-配置typescript测试

现代前端基本都是基于typescript开发,测试阶段也要同步使用typescript

demo

github: https://github.com/ACE0220/blog-demos/tree/main/test-framwork/jest-demo

如果对您有帮助,请给个star,谢谢~

依赖安装

1
2
3
pnpm add jest typescript ts-jest @jest/globals ts-node -D
# or
npm install -D jest typescript ts-jest @jest/globals ts-node

tsconfig.json

1
2
3
4
5
6
7
8
9
10
{
"compilerOptions": {
"target": "ES2018",
"module": "ES2020",
"rootDir": "./src",
"baseUrl": "./src",
"moduleResolution": "node",
"esModuleInterop": true
}
}

jest config file

在jest配置文件中,通过ts-jest预设集将esm转换成commonjs语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// rootdir/jest.config.ts
import type { JestConfigWithTsJest } from 'ts-jest';

const jestConfig: JestConfigWithTsJest = {
// [...]
preset: 'ts-jest/presets/default-esm',
extensionsToTreatAsEsm: ['.ts'],
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.js$': '$1',
},
testMatch: ['**/tests/*.test.ts'], // 指定任意文件夹下的test文件夹内的*.test.ts文件,才会被jest运行测试
transform: {
// '^.+\\.[tj]sx?$' to process js/ts with `ts-jest`
// '^.+\\.m?[tj]sx?$' to process js/ts/mjs/mts with `ts-jest`
'^.+\\.tsx?$': [
'ts-jest',
{
useESM: true,
},
],
},
};

export default jestConfig;

测试运行

在package.json中增加

1
2
3
4
5
6
// package.json
{
"scripts": {
"test": "jest --config jest.config.ts"
},
}

运行测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
npm run test

> jest-demo@1.0.0 test
> jest --config jest.config.ts

PASS tests/sum.test.ts
sum test
✓ add 1 + 2 to equal 3 (1 ms)

Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.688 s, estimated 1 s
Ran all test suites.

配置jest的typescript和esm支持就是这么简单,并没有还多复杂的操作,主要还是工具集的使用。

Author: ACE0220
Link: https://ace0220.github.io/tests/jest/intro-jest/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.