TypeScript實戰-26-Jest單元測試

一,前言

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

case

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章