Community程式設計與開發github.com

測試驅動開發

在實作任何功能或錯誤修復之前,先撰寫測試。

測試驅動開發 是什麼?

此技能強制執行測試驅動開發(TDD)流程:紅-綠-重構循環。它要求開發者在撰寫任何正式程式碼之前,先撰寫一個會失敗的測試(紅燈),接著撰寫剛好能讓測試通過的最低限度程式碼(綠燈),最後對程式碼進行重構以保證乾淨。技能文件中明確列出了常見的推託之詞(例如「太簡單不需要測試」、「之後再補測試」),並將其一一駁斥為危險的捷徑。它支援 TypeScript、JavaScript 及其他主流框架,強調必須親眼目睹測試失敗,才能確保測試的有效性。文件也涵蓋了錯誤修復情境、整合除錯,以及一個最終規則:正式程式碼若沒有先通過一個失敗的測試,就不能算是 TDD。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/obra/superpowers/tree/main/skills/test-driven-development

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

測試驅動開發 (TDD)

總覽

先寫測試。看著它失敗。寫最少的程式碼讓測試通過。

核心原則: 如果你沒有看到測試失敗,你就不知道它測試的是否正確。

違反規則的字面意義,就是違反規則的精神。

何時使用

永遠:

  • 新功能
  • Bug 修復
  • 重構
  • 行為變更

例外情況(請先詢問你的夥伴):

  • 拋棄式原型
  • 產生的程式碼
  • 設定檔

想「就這一次跳過 TDD」?停下來。那是合理化藉口。

鐵律

沒有先有失敗的測試,就不能有正式程式碼

先寫了程式碼?刪掉它。重新開始。

沒有例外:

  • 不要留著當「參考」
  • 不要在寫測試時「修改」它
  • 不要看它
  • 刪除就是刪除

從測試開始全新實作。就是這樣。

紅-綠-重構

digraph tdd_cycle {
    rankdir=LR;
    red [label="紅燈\n撰寫失敗測試", shape=box, style=filled, fillcolor="#ffcccc"];
    verify_red [label="確認正確\n失敗", shape=diamond];
    green [label="綠燈\n最小程式碼", shape=box, style=filled, fillcolor="#ccffcc"];
    verify_green [label="確認通過\n全部綠燈", shape=diamond];
    refactor [label="重構\n清理", shape=box, style=filled, fillcolor="#ccccff"];
    next [label="下一步", shape=ellipse];

    red -> verify_red;
    verify_red -> green [label="是"];
    verify_red -> red [label="錯誤的\n失敗"];
    green -> verify_green;
    verify_green -> refactor [label="是"];
    verify_green -> green [label="否"];
    refactor -> verify_green [label="保持\n綠燈"];
    verify_green -> next;
    next -> red;
}

紅燈 - 撰寫失敗測試

撰寫一個最簡單的測試,展示應該發生的行為。

<好的>

test('重試失敗的操作 3 次', async () => {
  let attempts = 0;
  const operation = () => {
    attempts++;
    if (attempts < 3) throw new Error('fail');
    return 'success';
  };

  const result = await retryOperation(operation);

  expect(result).toBe('success');
  expect(attempts).toBe(3);
});

名稱清楚,測試真實行為,只測一件事 </好的>

<不好的>

test('重試有效', async () => {
  const mock = jest.fn()
    .mockRejectedValueOnce(new Error())
    .mockRejectedValueOnce(new Error())
    .mockResolvedValueOnce('success');
  await retryOperation(mock);
  expect(mock).toHaveBeenCalledTimes(3);
});

名稱模糊,測試的是模擬物件而非程式碼 </不好的>

要求:

  • 一個行為
  • 清楚的名稱
  • 真實程式碼(除非不得已,否則不用模擬)

確認紅燈 - 看著它失敗

強制執行。絕對不能跳過。

npm test path/to/test.test.ts

確認:

  • 測試失敗(不是報錯)
  • 失敗訊息符合預期
  • 失敗是因為缺少功能(而不是打錯字)

測試通過了? 你在測試現有行為。修正測試。

測試報錯? 修正錯誤,重新執行直到它正確地失敗。

綠燈 - 最小程式碼

撰寫最簡單的程式碼讓測試通過。

<好的>

async function retryOperation<T>(fn: () => Promise<T>): Promise<T> {
  for (let i = 0; i < 3; i++) {
    try {
      return await fn();
    } catch (e) {
      if (i === 2) throw e;
    }
  }
  throw new Error('unreachable');
}

剛好能通過 </好的>

<不好的>

async function retryOperation<T>(
  fn: () => Promise<T>,
  options?: {
    maxRetries?: number;
    backoff?: 'linear' | 'exponential';
    onRetry?: (attempt: number) => void;
  }
): Promise<T> {
  // 你不需要它(YAGNI)
}

過度設計 </不好的>

不要新增功能、重構其他程式碼,或「改善」超出測試的範圍。

確認綠燈 - 看著它通過

強制執行。

npm test path/to/test.test.ts

確認:

  • 測試通過
  • 其他測試仍然通過
  • 輸出乾淨(沒有錯誤、警告)

測試失敗? 修正程式碼,不是修正測試。

其他測試失敗? 立刻修正。

「其他測試」指的是整個專案的測試套件,而不僅僅是你自己的檔案。 你寫的那個測試通過了,並不代表整個套件是綠燈。在宣告修改完成之前,即使你的任務只指定了一個測試檔案,也務必執行專案的測試指令(例如 pytest、npm test、cargo test——依該儲存庫使用的工具而定)。任務中的範圍陳述只界定交付項目,而不是你的驗證範圍。在該次執行中出現的任何失敗——包括不是你造成的失敗——都必須在你的報告中明確指出;如果你看著紅色測試滾過螢幕卻沒有提及,那就是因遺漏而造成的報告造假。

重構 - 清理

只有在綠燈後才能進行:

  • 消除重複
  • 改善命名
  • 提取輔助函式

保持測試為綠燈。不要新增行為。

重複

為下一個功能撰寫下一個會失敗的測試。

好的測試

品質好的不好的
最小一件事。名稱裡有「和」?拆開它。test('驗證電子郵件和網域和空白字元')
清楚名稱描述行為test('test1')
展示意圖展示期望的 API模糊了程式碼應該做的事

在撰寫或修改任何測試時,請閱讀 writing-good-tests.md 以了解保持測試誠實的規則:

  • 在撰寫測試之前,先說出會讓測試失敗的正式程式碼變更
  • 斷言應基於真實行為,絕不基於模擬行為
  • 只把測試專用的程式碼放在測試工具中,不要放在正式類別裡
  • 在模擬某個依賴項之前,先了解它的副作用

常見的合理化藉口

藉口現實
「太簡單了不需要測試」簡單的程式碼也會壞掉。測試只需 30 秒。
「我之後再測」之後才寫的測試會立刻通過——這證明不了任何事。它們可能測試了錯誤的東西、測試了實作而非行為,或者漏掉你忘記的邊界情況。你從未看著它失敗,所以你從未證明它能抓出 bug。測試先行強迫了這種失敗。
「後測也能達到相同目標(重在精神而非形式)」後測回答的是「這段程式碼做了什麼?」;先測回答的是「這段程式碼應該做什麼?」後寫的測試會被你已經寫好的程式碼偏誤——你驗證的是你記得的案例,而不是你會發現的案例。有覆蓋率卻沒有測試有效的證明。
「已經手動測試過了」手動測試是臨時性的:沒有你測試了哪些地方的記錄,無法在程式碼變更時重新執行,壓力下容易忘記案例。「我試了能用」並不代表全面。自動化測試每次都依相同方式執行。
「刪掉 X 小時的心血太浪費了」這是沈沒成本謬誤——那些時間無論如何都已經花掉了。真正的選擇是:用 TDD 重寫(高信心度) vs. 保留它並事後補上測試(低信心度,很可能有 bug)。保留你無法信任的程式碼才是浪費。
「留著當參考,然後先寫測試」你會修改它。那就是後測。刪除就是刪除。
「需要先探索一下」可以。丟掉探索結果,從 TDD 開始。
「測試很難寫 = 設計不清楚」聽從測試的意見。難測 = 難用。
「TDD 會拖慢我的速度」TDD 就是務實的路徑:在提交前抓住 bug、防止回歸、讓你能放心重構。「務實」的捷徑意味著在生產環境除錯——更慢,而不是更快。
「手動測試比較快」手動測試無法證明邊界情況。每次變更你都得重新測試。
「現有程式碼沒有測試」你正在改善它。為現有程式碼新增測試。

紅旗 - 停止並重新開始

  • 先寫程式碼再寫測試
  • 實作後才測試
  • 測試立刻通過
  • 無法解釋測試為何失敗
  • 「之後再補」測試
  • 合理化「就這一次」
  • 「我已經手動測試過了」
  • 「後測也能達到相同目的」
  • 「重要的是精神不是形式」
  • 「留著當參考」或「修改現有程式碼」
  • 「已經花了 X 小時,刪掉太浪費」
  • 「TDD 太教條了,我要務實一點」
  • 「這次情況不同因為…」

以上所有情況都意味著:刪除程式碼。用 TDD 重新開始。

範例:Bug 修復

Bug: 空的電子郵件被接受

紅燈

test('拒絕空白的電子郵件', async () => {
  const result = await submitForm({ email: '' });
  expect(result.error).toBe('必須填寫電子郵件');
});

確認紅燈

$ npm test
FAIL: 預期得到 '必須填寫電子郵件',卻得到 undefined

綠燈

function submitForm(data: FormData) {
  if (!data.email?.trim()) {
    return { error: '必須填寫電子郵件' };
  }
  // ...
}

確認綠燈

$ npm test
PASS

重構 如有需要,提取驗證邏輯以處理多個欄位。

驗證檢查清單

在標記工作完成之前:

  • 每個新函式/方法都有測試
  • 在實作之前,已觀察到每個測試失敗
  • 每個測試失敗的原因都符合預期(缺少功能,不是打錯字)
  • 撰寫了最低限度的程式碼來通過每個測試
  • 所有測試通過
  • 輸出乾淨(沒有錯誤、警告)
  • 測試使用真實程式碼(除非不得已,否則不用模擬)
  • 涵蓋了邊界情況和錯誤處理

無法勾選所有項目?你跳過了 TDD。重新開始。

卡住時怎麼辦

問題解決方案
不知道怎麼測試撰寫你希望的 API。先寫斷言。詢問你的夥伴。
測試太複雜設計太複雜。簡化介面。
什麼都得模擬程式碼耦合度太高。使用依賴注入。
測試設定很龐大提取輔助函式。仍然複雜?簡化設計。

除錯整合

找到 bug?撰寫一個能重現它的失敗測試。遵循 TDD 循環。測試證明了修復並防止回歸。

絕不要不寫測試就修復 bug。

最終規則

正式程式碼 → 測試存在且先失敗
否則 → 不是 TDD

未經你的夥伴許可,沒有任何例外。

Individual skills in this repo

This repo contains 14 individual skills — each has its own dedicated page.

brainstorming

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).

diagnosing-superpowers

Use when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.

dispatching-parallel-agents

Use when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies

executing-plans

Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available

finishing-a-development-branch

Use when implementation is complete, all tests pass, and you need to decide how to integrate the work

receiving-code-review

Use when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation

requesting-code-review

Use when completing tasks, implementing major features, or before merging to verify work meets requirements

subagent-driven-development

Use when executing implementation plans with independent tasks in the current session

systematic-debugging

Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes

using-git-worktrees

Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback

using-superpowers

Use when starting any conversation - establishes how to find and use skills, requiring skill invocation before ANY response including clarifying questions

verification-before-completion

Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always

writing-plans

Use when you have a spec or requirements for a multi-step task, before touching code

writing-skills

Use when creating new skills, editing existing skills, or verifying skills work before deployment

相關技能