跳至主要内容

測試的基礎

Basic Test File & Project Setup

單元通常是函式,也可以是類別。可以稱之為單元的函式, 原則上只處理單純、少量的工作,盡量避免在函式主體調用其他函式。

編碼慣例

  • 測試檔案與單元檔案建立於同一資料夾
  • 測試檔命名慣例(二擇一)
    單元檔案名稱.test.副檔名
    單元檔案名稱.spec.副檔名
  • 單元測試函式
    it()
    test()
    測試框架通常將測試函式命名為 it 或 test

Writing a First Test

it('描述預期結果', 匿名函式);

測試函式範例
it("should output a number", () => {});

expect(結果).to...(符合某些情況)

測試函式範例
it("should output a number", () => {
const result = testedFunc();
expect(result).toBe(); // 除了 toBe 還有許多斷言函式
});

若腳本設定無誤,終端幾可輸入 $ npm test,藉此執行測試。

The AAA Pattern - Arrange, Act, Assert

  • Arrange 定義測試環境與值
  • Act 執行需要通過測試的代碼或函式
  • Assert 評估產出的值或結果,並將之與預期的值或結果相互比較。

Keep Your Tests Simple!

測試檔應保持簡潔明瞭,以確保協作人員易讀或多年後回顧時的易讀。

Defining Behaviors & Fixing Errors In Your Code

為確認一個單元可否通過測試,可能需要不只一個測試函式。

Demo: Writing More Tests

Writing good tests is an iterative process.

Testing For Errors

開發者可透過測試檢視單元是否會在該拋出錯誤時拋出錯誤。
但為避免測試因單元拋出錯誤而無法通過,編寫測試函式時,
應宣告一個負責調用單元函式的函式。

it("should throw an error if no values is passed into the function", () => {
const resultFn = () => {
add(); // add 是需接受測試的單元
};

expect(resultFn).toThrow();
});

Tests With Multiple Assertions (Multiple Expectations)

增加斷言前
it("should yield NaN for non-transformable values", () => {
const input = "invalid";
const result = transformToNumber(input);
expect(result).toBeNaN();
});

有時會需要不只一個 Act 或 Assertion 以確保單元正確無誤。
例如以上測試可以再增加斷言以提升精確度。

增加斷言後
it("should yield NaN for non-transformable values", () => {
const input = "invalid";
const input2 = {};

const result = transformToNumber(input);
const result2 = transformToNumber(input2);

expect(result).toBeNaN();
expect(result2).toBeNaN();
});

Introducing Test Suites

一個測試檔的測試對象可能是多個單元,每個單元可能需要通過多項測試。
倘若測試檔僅由 it() 構成,當測試項目眾多時,可能難以從測試報告的錯誤當中找到錯誤的所在位置。
因此通常會利用 describe() 將多項測試歸納為 Test Suite。
通常一個單元只需要歸納為一個 Test Suite,但也可視情況建立巢狀 Test Suite。

Test Suite 範例
describe("unit name", () => {
it("should... (test 1)", () => {
// AAA Pattern
});

it("should... (test 2)", () => {
// AAA Pattern
});

it("should... (test 3)", () => {
// AAA Pattern
});
});
備註

目前用過的方法
describe()
it ()
expect()
not toBe()
toThrow()
toBeNaN()
toBeTypeOf()