1. 程式人生 > 其它 >前端單元測試之Jest初體驗

前端單元測試之Jest初體驗

Jest 是一個令人愉快的 JavaScript 測試框架,專注於簡潔明快。Jest 擁有良好的文件,只需很少的配置,並能根據你的需求進行擴充套件。它能確保任何 JavaScript 程式碼的正確性。它為你提供了易於理解、熟悉且功能豐富的 API 來編寫測試用例,並快速地反饋結果。

一、jest優勢

  1. 零配置: Jest 的目標是在大部分 JavaScript 專案上實現開箱即用, 無需配置。
  2. 快照: 能夠輕鬆追蹤大型物件的測試。 快照可以與測試程式碼放在一起,也可以整合進程式碼行內。
  3. 隔離: 測試程式擁有自己獨立的程序 以最大限度地提高效能。
  4. 優秀的 api:itexpect - Jest
    將整個工具包放在同一個 地方。好書寫、好維護、非常方便。

二、安裝

  • 全域性安裝:
npm i -g jest
# or
cnpm i -g jest
# or
yarn global add jest
  • 專案區域性安裝:
npm i -D jest
# or
cnpm i -D jest
# or
yarn add --dev jest

三、配置使用

  1. 初始化專案,生成 package.json 檔案和 jest 自定義配置檔案
# 初始化,生成 package.json 檔案
npm init -y

# 建立一個 jest 基礎配置檔案
jest --init 
  1. 配置 scripts
    指令碼命令。
{
  "scripts": {
    "test": "jest",
    "test:config": "jest test_dir --notify --config=config.json ",
    "test:output": "jest test_dir --outputFile=test.report.json --json"
  }
}

命令解釋:

# 全域性搜尋 test.js 字尾檔案執行單元測試
npm run test

# 使用 config.json 自定義配置檔案進行單元測試
npm run test:config

# 將測試結果輸出儲存到 json 檔案
npm run test:output

四、example

  1. 建立一個 demo.js 檔案,編寫功能函式並 exports 匯出。
// ./demo.js

function sum(a, b) {
  return a + b;
}

function sort(arr=[]) {
  return arr.sort()
}

module.exports = {
  sum,
  sort,
}
  1. 建立一個 __tests__ 資料夾,並生成 demo.test.js 單元測試檔案。
// ./__tests__/demo.test.js

const { sum, sort } = require('../demo.js')

test('測試sum方法:10 + 20 = 30', () => {
  expect(sum(10, 10)).toBe(30);
})

describe('測試 sort 方法功能', ()=>{
  it('正常測試', ()=>{
    const data = sort([1,3,5,2,4]);
    expect(data).toEqual([1,2,3,4,5]);
  })
  it('不傳值', ()=>{
    const data = sort();
    expect(data).toEqual([]);
  })
})
  1. 使用 npm test 執行單元測試。
npm test
  1. 輸出
 PASS  ../demo.test.js
  √ 測試sum方法:10 + 20 = 30 (3 ms)
  測試 sort 方法功能
    √ 正常測試 (1 ms)
    √ 不傳值 (1 ms)

Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        0.976 s, estimated 2 s
Ran all test suites matching /.\\demo.test.js/i.
  1. sumsort 方法單元測試通過。

五、jest總結

  1. 當使用 jest 未指定測試的目錄或具體檔案時,會預設查詢 __tests__ 資料夾下的 js|ts 檔案和以 test.js 為字尾的檔案。
  2. 建議所有的單元測試檔案集中存放到單獨的 __tests__ 目錄下,與業務功能程式碼隔離。
  3. 推薦使用以功能方法名 + .test.js 的形式來命名對應的測試檔案,例如:一個求和功能方法所在的檔案為 sum.js,對應的單元測試檔案就是 sum.test.js
  4. 常用的判斷型別:toBe (值型別)、toEqual (引用型別)、toBeNulltoBeDefinedtoBeTruthy (true)、toBeFalsy (false)、toBeCloseTo (約等於)、toMatch (匹配包含)、toThrownot 修飾符( not.toBe )。
  5. describe 搭配 it 相當於形成了一組測試,適用於一個功能方法對應了多個測試用例。

參考文件:

  1. https://www.jestjs.cn/docs/getting-started

歡迎訪問:天問部落格