Skip to content

規範-測試描述

撰寫清楚的測試描述(test description)能幫助團隊快速理解功能邏輯、錯誤行為與測試目的,是提升可讀性與維護性的關鍵。

語言選用

  • 測試描述: 推薦使用英文,因為測試程式碼是程式碼的一部分,與程式碼語言一致(大多為英文)較一致、通用。
  • 註解: 中英皆可

✍️ 常用句型與範例

測試描述應回答三個問題: Given(背景條件) + When(動作) + Then(期望)

或是也可以理解為 輸入...輸出...

✅ 常用句式模板:

  • 輸入: 描述 背景狀態/條件/執行某某動作時

    • when...,
    • should...when...
    • before...,
    • after...,
    • if...,
    • default..(style/status/content)..should be...
    • should initially... or ...initially...by default...on initial load
  • 輸出: 描述 應為某某狀態、樣式/去做某某動作

    • returns...throws...
    • sth. is/has/should be...(status/style)
    • (should) show...(el/text)
    • (should) renders...(el/text)
    • (should) calls...(api)
    • (should) triggers...(action)
    • (should) changes/updates...(other/itself)
    • (should) goes to...(route)

範例

js
// 當 nav 為 active 狀態時,應將 nav 標題下劃線
test('should underline the nav title when active', () => {});

// 當按鈕被懸停時,會有較暗的背景
test('the button has a darker background on hover', () => {});

// 當被點擊時,去詳細頁面
test('when clicked, goes to the details page', () => {});

// 初始應渲染一張圖片
test('should initially render an image', () => {});

// 初始應渲染 hello 字串
test("render 'hello' by default", () => {});

// 沒有輸入時應該回傳預設值
it('should return default value when no input is given', () => {});

// 無效輸入時應該拋出錯誤
it('returns error when input is invalid', () => {});

// 條件不成立時不應更新狀態
it('does not update state if condition is false', () => {});

// 點擊按鈕後應觸發 fetchData
it('calls fetchData when button is clicked', () => {});

// 缺少設定時應拋出錯誤
it('throws error when config is missing', () => {});

new user should be inactive by default

new order should have status "pending"

new item should have default quantity of 1

📚 群組描述(describe)

使用 describe 可以按功能或情境分類測試案例,讓整體結構更清楚。

建議分組依據:

分組依據範例
函式名稱describe('parseNumber', () => { ... })
功能場景describe('when user is logged in', () => { ... })
邏輯區塊describe('edge cases', () => { ... })
錯誤處理邏輯describe('throws when invalid config', () => {})

✅ 撰寫規範

  • 敘述要具體,避免模糊用語
→ 太模糊
❌ it('works')
❌ it('test something')
❌ it('handles case')

→ 清楚指出行為與條件
✅ it('returns false when input is null')
✅ it('displays error message when login fails')
✅ it('disables submit button when form is invalid')
  • 描述應包含「操作條件」與「預期結果」
❌ it('returns true')
✅ it('returns true when email format is valid')
  • 避免加入實作細節,與程式碼過於耦合
❌ it('calls doSomething function internally') → 綁定實作細節 (變更函式名會讓測試壞掉)
✅ it('triggers search action when user presses Enter') → 闡述對外行為