No slash command · from useful-skills
Unit Test 與 Integration Test 的寫作風格規範:檔頭註解、測試命名、段落排版、import 分群、斷言寫法、錯誤路徑組織。本 skill 專注在「測試程式碼本身怎麼排版、怎麼寫註解、怎麼組織結構」。當撰寫或 review 測試程式碼的格式與風格時使用。
Ships in useful-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
本 skill 規範測試程式碼的排版、註解、命名、結構。不綁定語言或框架,但範例以 TypeScript + Jest 風格呈現(觀念通用)。
本 skill 只管「測試程式碼怎麼寫才好讀好維護」(排版、命名、斷言、結構);「測什麼、怎麼選 mock」的方法論不在範圍內。
每份測試檔頂端寫一個 JSDoc block,包含四個欄位:
/**
* <測試類型> — <被測對象>
*
* Scope: <被測物呼叫了哪些層>
* Mocks: <哪些依賴被替換 / 無>
* SUT: <被測的函式或 method 全名>
*
* 目的:<一句話說明這組測試要驗證什麼>
*/
Integration test:
/**
* Integration test — OrderService.placeOrder
*
* Scope: Service → Repository → DB (real)
* Mocks: 無 — 所有資料存取走真 DB
* SUT: OrderService.placeOrder(userId, items)
*
* 目的:驗證下單流程的資料一致性 — 庫存扣減、訂單建立、wallet 扣款
*/
Unit test:
/**
* Unit test — expandRewardItem
*
* Scope: 純函式,無外部依賴
* Mocks: 無
* SUT: expandRewardItem(spec)
*
* 目的:驗證獎勵展開邏輯 — VOICE_POSTCARD 按數量拆分、COIN 保持單筆
*/
有 mock 的 unit test:
/**
* Unit test — NotificationService.sendReminder
*
* Scope: Service(邏輯層)
* Mocks: EmailClient (stub), UserRepository (stub)
* SUT: NotificationService.sendReminder(userId)
*
* 目的:驗證發送條件判斷 — 已讀不發、未讀才發、過期不發
*/
當一個 describe 裡有 3 個以上的 it,在 describe 前加一個編號索引:
/**
* 測試情境一覽:
*
* 1. 正常下單 → 庫存扣減、訂單建立、wallet 扣款、回傳 receipt
* 2. 混合商品(實體 + 虛擬)→ 各走不同出貨流程
* 3. 已下過同樣的單 → 冪等,回傳既有訂單
* 4. 庫存不足 → throw
* 5. wallet 餘額不夠 → throw、庫存不變
* 6. userId 不存在 → throw
*/
describe("OrderService.placeOrder (integration)", () => {
it 的順序保持一致格式:ClassName.methodName (test type)
describe("UserService.createUser (unit)", () => { ... });
describe("OrderService.placeOrder (integration)", () => { ... });
describe("expandRewardItem (unit)", () => { ... }); // 純函式不用 class 名
(unit) / (integration) 標記讓跑測試時一眼分辨describe("UserService.createUser (unit)", () => {
describe("when email is valid", () => { ... });
describe("when email already exists", () => { ... });
});
讀 it 名稱就該知道「什麼情境 → 什麼結果」,不需要打開 test body。
<前提條件>時,<預期行為>(用該專案的語言)
// ✅ 好
it("餘額不足時,轉帳失敗且雙方帳戶不變", ...)
it("email 已存在時,拋出 DuplicateEmailError", ...)
it("returns empty array when no items match the filter", ...)
it("庫存剛好等於訂購量時,下單成功且庫存歸零", ...)
// ❌ 壞
it("createUser works", ...)
it("test case 1", ...)
it("should create user", ...) // 少了「什麼情境」
it("placeOrder", ...)
不一定。如果多個斷言是「同一件事的不同面向」,可以留在同一個 it:
// ✅ OK — 都是「下單成功」這件事的不同面向
it("正常下單時,庫存扣減、訂單建立、wallet 扣款", ...)
// ❌ 應該拆 — 這是兩件獨立的事
it("下單成功且推播通知寄出", ...)
判斷標準:如果其中一個斷言 fail 了,另一個還有獨立意義嗎?有 → 拆。沒有 → 合。
it("正常下單時,庫存扣減且訂單建立", async () => {
// Arrange
const user = await createUser();
const product = await createProduct({ stock: 10 });
// Act
const result = await orderService.placeOrder(user.id, [{ productId: product.id, qty: 3 }]);
// Assert
const updatedProduct = await getProduct(product.id);
expect(updatedProduct.stock).toBe(7);
expect(result.orderId).toBeDefined();
});
或用 // When / // Then(較簡潔,適合 Arrange 段落很明顯的情況):
it("正常下單時,庫存扣減且訂單建立", async () => {
const user = await createUser();
const product = await createProduct({ stock: 10 });
// When
const result = await orderService.placeOrder(user.id, [{ productId: product.id, qty: 3 }]);
// Then
const updatedProduct = await getProduct(product.id);
expect(updatedProduct.stock).toBe(7);
});
如果 Act 需要多行,這個 test 可能在測兩件事,考慮拆開。
分三個區塊,區塊之間空一行:
// 1. 外部套件 / 語言標準庫 / 型別
import { randomUUID } from "crypto";
import { OrderStatus, PaymentType } from "@prisma/client";
// 2. App 模組(被測對象及其依賴)
import { prisma } from "@/configs/database";
import orderService from "@/services/order.service";
// 3. Test helpers
import { truncateAll } from "@tests/helpers/db.helper";
import { createUser, createProduct } from "@tests/helpers/order.factory";
呼叫 SUT 後,不只看回傳值,還要去資料源(DB / 檔案 / 外部狀態)確認實際寫入:
// Act
const result = await service.placeOrder(userId, items);
// Assert — 驗回傳值
expect(result.message).toBe("Order placed");
// Assert — 回 DB 確認
const order = await db.order.findFirst({ where: { userId } });
expect(order.status).toBe("CREATED");
const product = await db.product.findFirst({ where: { id: productId } });
expect(product.stock).toBe(7); // 原本 10,買了 3
toMatchObject只斷言你關心的欄位,不要逐欄比對所有欄位(加新欄位就壞):
// ✅ 只比對關心的
expect(order).toMatchObject({
status: "CREATED",
totalAmount: 300,
});
// ❌ 比對所有欄位(脆弱)
expect(order.status).toBe("CREATED");
expect(order.totalAmount).toBe(300);
expect(order.createdAt).toBeInstanceOf(Date); // 不必要
expect(order.updatedAt).toBeInstanceOf(Date); // 不必要
toMatchObject vs toEqual — 用哪個看「這物件多一個欄位時,測試該不該紅」:
toEqual 把整包 pin 住。適用:assembled 輸出 / mapper 結果 / 小 value object / 要發出去的 wire payload(多一欄可能是洩漏、少一欄是壞掉,就是要它變動時強迫你回來確認)。toMatchObject 只驗你關心的。注意上面那個 ❌ 比對所有欄位 是逐欄 .toBe()(脆弱、又漏驗沒列到的欄位)——它跟整包 toEqual({...}) 是兩回事。toMatchObject 是「大物件、只 care 幾欄」的預設;但當確切形狀本身就是契約時(尤其對外 payload),toEqual 才對,別為了怕「加欄位就壞」而把該 pin 死的契約放掉。
expect.objectContainingexpect(result).toMatchObject({
items: [
expect.objectContaining({ name: "Widget", qty: 3 }),
expect.objectContaining({ name: "Gadget", qty: 1 }),
],
});
// 先確認數量對
expect(order.items).toHaveLength(2);
// 再驗個別項目
const widget = order.items.find((i) => i.name === "Widget");
expect(widget).toMatchObject({ qty: 3, price: 100 });
當每筆預期相同時,用 for-of:
expect(snapshots).toHaveLength(3);
for (const snap of snapshots) {
expect(snap.status).toBe("CLAIMED");
expect(snap.quantity).toBe(1);
}
it.each(或框架等價物)it.each(["EXPIRED", "SUSPENDED", "CANCELLED"])(
"狀態是 %s 時,操作會 throw",
async (status) => {
const order = await createOrder({ status });
await expect(service.ship(order.id)).rejects.toThrow();
}
);
除非「副作用沒發生」本身就是被測行為(例如:餘額不足時 wallet 不變),否則錯誤路徑只驗 throw:
// ✅ 只驗 throw
await expect(service.placeOrder(fakeUserId, items)).rejects.toThrow();
// ✅ 「副作用沒發生」是重點行為時才加
await expect(service.placeOrder(userId, items)).rejects.toThrow("Insufficient");
const wallet = await db.wallet.findFirst({ where: { userId } });
expect(wallet.balance).toBe(originalBalance); // 沒被扣
驗證「已完成的操作再次呼叫不會重複執行」:
it("訂單已出貨時,再次呼叫 ship 不重複出貨,回傳既有結果", async () => {
// Arrange — 手動建立「已出貨」的完整狀態
const order = await createOrder({ status: "SHIPPED" });
const existingShipment = await createShipment({ orderId: order.id });
// Act
const result = await service.ship(order.id);
// Assert — 回傳既有結果,不新建
expect(result.shipmentId).toBe(existingShipment.id);
const shipments = await db.shipment.findMany({ where: { orderId: order.id } });
expect(shipments).toHaveLength(1); // 沒有多出一筆
});
關鍵:Arrange 手動建完整的「已完成」狀態,不是先呼叫一次 SUT 再呼叫第二次。這樣做測試更快、更不依賴 SUT 的其他行為。
在 describe 內按這個順序排列 it:
it.each 收攏)it.each 收攏,不會佔版面it 時有測試情境索引describe 標記了 (unit) 或 (integration)it 名稱讀得出「什麼情境 → 什麼結果」toMatchObject 而非逐欄比對it.each 收攏What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub lystyp/useful-skill --plugin useful-skills19 skills in this plugin
/ai-family-backend-styleai_family_backend / backend-v2 專案的 coding style 與實作 tips — 分層架構(Controller → Service → Repository)、Zod validator 慣例、Import 分群、Prisma + Exception 處理、Pagination、Swagger/Router/Service/Repository 的新增流程、SRP 檢查四問、Commit 規範。當在 /Users/daniel.shi/hephai/ai_family_backend 這個 repo 內寫或改 code(特別是 controllers/services/repository/validators/routes/swagger)時觸發。/backend-repo-onboarding讓後端工程師在最短時間內從「看得懂字」變成「敢改」一個陌生的後端 repo。做法是先實地求證產出一份上手文件(目錄職責與依賴方向、對應到他原本熟的分層、可執行的架構驗證指令、一條讀路徑與一條寫路徑、交易邊界與錯誤轉換、改動迴路、語法與慣例路障),再照那份文件一步步導覽,隨時接「貼一行 code 問這是什麼」。當使用者說「我要怎麼讀這個專案」「幫我熟悉這個 repo」「我接手了一個專案」「這個後端是怎麼設計的」「每個資料夾是做什麼用的」「新人怎麼上手」「帶我看一下這個後端」「這專案怎麼分層」「我第一次碰這個語言的後端」時務必觸發。即使他只丟一個局部問題(例如「api path 寫在哪」「這個資料夾幹嘛的」),也先照常回答,然後用一句話提議把剩下的補齊成一份上手文件——因為他要的通常不只是那一題。不要觸發:已經熟這個 repo 的人問某支功能在哪、純 bug 排查、跟任何 repo 無關的語言教學、或只是要做 code review。/Other plugins' skills for the same job