TypeScript + jest + VSCode 編寫單元測(cè)試

在 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)試

參考:vscode-recipes - debugging-jest-tests

我們?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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容