在 TypeScript 開發(fā)中,我們需要為開發(fā)的模塊編寫單元測(cè)試,可以使用 jest 這個(gè)框架??蓞⒖?npm - jest
如果你已經(jīng)有一個(gè) TypeScript 項(xiàng)目,現(xiàn)在要為其添加測(cè)試用例。步驟如下:
1. 安裝 jest 依賴
首先使用下面的命令安裝 npm 依賴:
npm install -D jest ts-jest @types/jest
2. 配置 jest
2.1. package.json
{
// ...
"scripts": {
"build": "tsc",
"test": "jest",
"test-c": "jest --coverage"
},
"jest": {
"testEnvironment": "node"
},
// ...
}
2.2. jest.config.js
在項(xiàng)目根目錄新建 jest.config.js 文件,如下:
module.exports = {
roots: [
"<rootDir>/test"
],
testRegex: 'test/(.+)\\.test\\.(jsx?|tsx?)$',
transform: {
"^.+\\.tsx?$": "ts-jest"
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};
3. 編寫 test 用例
當(dāng)前,我們的項(xiàng)目目錄結(jié)構(gòu)如下:
your-project
|- src
| |- HelloWorld.ts
| |- ...
|
|- package.json
|- tsconfig.json
|- jest.config.js
|
|- test
| |- HelloWorld.test.ts
| |- ...
|
我們的 HelloWorld.test.ts 編寫如下:
/**
* HelloWorld.test.ts
*/
import hello from '../src/HelloWorld';
test('hello world test', () => {
expect(hello('message')).toBe(true);
});
然后執(zhí)行 npm run test 即可運(yùn)行測(cè)試用例。
4. 覆蓋率報(bào)告
我們?nèi)绻氲玫矫啃写a的覆蓋率執(zhí)行報(bào)告,可以使用 npm run test-c 命令,它其實(shí)是在執(zhí)行 jest 的時(shí)候帶了 --coverage 參數(shù)。生成的報(bào)告如下:

file-list
點(diǎn)開具體的文件,可以看到每行的執(zhí)行覆蓋情況:

file-details
5. VSCode 調(diào)試
我們?nèi)绻?VSCode 環(huán)境下,需要調(diào)試用例,則可以進(jìn)行如下配置,在 .vscode/launch.json 文件中:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Jest All",
"program": "${workspaceFolder}/node_modules/.bin/jest",
"args": ["--runInBand"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true,
"windows": {
"program": "${workspaceFolder}/node_modules/jest/bin/jest",
}
},
{
"type": "node",
"request": "launch",
"name": "Jest Current File",
"program": "${workspaceFolder}/node_modules/.bin/jest",
"args": [
"${fileBasenameNoExtension}",
"--config",
"jest.config.js"
],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true,
"windows": {
"program": "${workspaceFolder}/node_modules/jest/bin/jest",
}
}
]
}
然后在左側(cè) Debug Panel 進(jìn)行調(diào)試,可以選擇 Jest All 調(diào)試所有 test 文件;或者選擇 Jest Current File 調(diào)試當(dāng)前選中的 test 文件。如下:

jest debug