Coverage Guard
確保任何 JavaScript/TypeScript 專案達到 100% 測試覆蓋率。自動偵測測試執行器,在缺少時設定測試基礎設施,為未覆蓋的元件撰寫測試,並循環直到每個檔案都達到 100% 覆蓋率。
概述
此技能遵循完整的管線:
- 偵測 執行器與基礎設施 → 2. 掃描 原始碼與測試 → 3. 設定(若缺少) → 4. 產生 新測試 → 5. 執行 覆蓋率 → 6. 填補 缺口 → 7. 驗證 → 重複直到 100%
逐步工作流程
階段 1:偵測環境
檢查專案根目錄的 package.json 以判斷:
cat package.json
辨識測試執行器與覆蓋率工具:
| 指標 | 執行器 | 覆蓋率指令 |
|---|---|---|
"vitest" 位於 devDependencies | Vitest | npx vitest --coverage |
"jest" 位於 devDependencies | Jest | npx jest --coverage |
"react-scripts" 位於 devDependencies | react-scripts (Jest) | npx react-scripts test --coverage |
"next" 位於 devDependencies | Next.js (Jest) | npx next test --coverage 或檢查 jest.config |
"@angular/core" 位於 dependencies | Angular (Karma/Jasmine) | ng test --code-coverage |
"@playwright/test" 位於 devDependencies | Playwright | npx playwright test(無內建覆蓋率;使用 @playwright/test 搭配 istanbul) |
"mocha" 位於 devDependencies | Mocha | npx mocha(透過 c8/nyc 進行覆蓋率) |
"cypress" 位於 devDependencies | Cypress | npx cypress run(透過 @cypress/code-coverage 進行覆蓋率) |
"ava" 位於 devDependencies | AVA | npx ava(透過 c8 進行覆蓋率) |
| 無發現 | 無 → 前往階段 2 → 階段 3 設定 |
階段 2:掃描原始檔與現有測試
找出所有需要測試的原始檔(元件、模組、工具):
# 常見原始碼目錄
find src -type f \( -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx" \) ! -name "*.test.*" ! -name "*.spec.*" ! -name "*.d.ts" ! -path "*/node_modules/*" ! -path "*/dist/*" ! -path "*/build/*" ! -path "*/.next/*"
找出所有現有測試檔案:
find src -type f \( -name "*.test.*" -o -name "*.spec.*" \) ! -path "*/node_modules/*"
將每個原始檔對應到一個測試檔:
src/components/Button.tsx→src/components/Button.test.tsx或src/components/__tests__/Button.test.tsxsrc/utils/format.ts→src/utils/format.test.ts或src/utils/__tests__/format.test.ts- 遵循現有專案中測試檔案放置的慣例
分類每個原始檔:
- 有測試 → 加入覆蓋率分析清單
- 無測試 → 標記為需要產生測試
階段 3:設定測試基礎設施(若缺少)
如果在階段 1 中未偵測到測試執行器,以互動方式詢問使用者:
? 未偵測到測試框架。您想要設定哪一個?
1) Vitest(推薦 — 快速、現代、原生 ESM)
2) Jest(最廣泛使用)
3) react-scripts(Create React App)
4) 無 — 跳過,我會手動設定
一旦使用者選擇,安裝相依套件並建立設定檔:
Vitest 設定:
npm install -D vitest @vitest/coverage-v8
建立 vitest.config.ts:
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
exclude: [
'**/node_modules/**',
'**/dist/**',
'**/*.config.*',
'**/*.d.ts',
],
},
},
})
加入 package.json 的 scripts:
{
"scripts": {
"test": "vitest",
"test:coverage": "vitest --coverage"
}
}
Jest 設定:
npm install -D jest @types/jest ts-jest
npx ts-jest config:init
npm install -D jest @testing-library/react @testing-library/jest-dom jest-environment-jsdom
建立 jest.config.ts:
export default {
testEnvironment: 'jsdom',
transform: {
'^.+\.tsx?$': 'ts-jest',
},
coverageReporters: ['text', 'json', 'html'],
collectCoverageFrom: ['src/**/*.{ts,tsx}', '!src/**/*.d.ts'],
}
加入 package.json 的 scripts:
{
"scripts": {
"test": "jest",
"test:coverage": "jest --coverage"
}
}
react-scripts 設定:
npm install -D @testing-library/react @testing-library/jest-dom @testing-library/user-event
覆蓋率已內建:
{
"scripts": {
"test": "react-scripts test",
"test:coverage": "react-scripts test --coverage"
}
}
設定完成後,執行快速測試以確認一切正常運作:
npm test
如果失敗,請先修正設定問題再繼續。
階段 4:為未測試的原始檔撰寫測試
對於每個沒有測試檔的原始檔,分析原始碼:
- 讀取原始檔
- 識別:
- 所有匯出的函式、類別、元件
- 回傳型別與可能的回傳路徑
- 參數及其型別(必要、選用、預設值)
- Props 介面(針對 React 元件)
- 非同步行為(Promises、async/await)
- 副作用(API 呼叫、localStorage 等)
- 錯誤狀態與邊界案例
- 依照專案慣例產生測試檔:
- 使用偵測到的測試執行器 API(Jest/Vitest 的
describe/it/expect等) - 對於 React:使用
@testing-library/react(render、screen、fireEvent) - Mock 外部相依套件
- 涵蓋所有分支、邊界案例與錯誤路徑
- 使用偵測到的測試執行器 API(Jest/Vitest 的
React 元件範例(src/components/Button.tsx → src/components/Button.test.tsx):
import { render, screen, fireEvent } from '@testing-library/react'
import { Button } from './Button'
describe('Button', () => {
it('使用標籤渲染', () => {
render(<Button label="點擊我" />)
expect(screen.getByText('點擊我')).toBeInTheDocument()
})
it('點擊時呼叫 onClick', () => {
const onClick = vi.fn() // Jest 使用 jest.fn()
render(<Button label="點擊" onClick={onClick} />)
fireEvent.click(screen.getByText('點擊'))
expect(onClick).toHaveBeenCalledTimes(1)
})
it('當 disabled prop 為 true 時被禁用', () => {
render(<Button label="點擊" disabled />)
expect(screen.getByText('點擊')).toBeDisabled()
})
})
工具函式範例(src/utils/format.ts → src/utils/format.test.ts):
import { formatCurrency, truncate } from './format'
describe('formatCurrency', () => {
it('格式化整數金額', () => {
expect(formatCurrency(1000)).toBe('$1,000.00')
})
it('格式化小數金額', () => {
expect(formatCurrency(99.95)).toBe('$99.95')
})
it('處理零', () => {
expect(formatCurrency(0)).toBe('$0.00')
})
it('處理負數', () => {
expect(formatCurrency(-50)).toBe('-$50.00')
})
})
階段 5:執行覆蓋率報告
根據偵測到的執行器執行適當的覆蓋率指令:
| 執行器 | 指令 |
|---|---|
| Vitest | npx vitest --coverage --reporter=verbose |
| Jest | npx jest --coverage --verbose |
| react-scripts | npx react-scripts test --coverage --watchAll=false |
| 其他 | 使用專案設定的覆蓋率指令 |
解析輸出以識別:
- 低於 100% 覆蓋率的檔案
- 未覆蓋的行、分支、函式與陳述式
- 需要測試的特定行號
- 覆蓋率為 0% 的檔案(無測試存在)
階段 6:分析並填補覆蓋率缺口
對於每個低於 100% 的檔案(包括階段 4 中已有測試但未達 100% 的檔案):
- 並排讀取原始檔及其測試檔
- 了解未覆蓋的行/函式/分支在做什麼
- 識別測試中遺漏的邊界案例
- 撰寫有針對性的測試以覆蓋缺口:
- 未覆蓋的分支:測試
if和else路徑、三元條件 - 未覆蓋的函式:測試所有可能的回傳路徑
- 未覆蓋的行:追蹤邏輯並撰寫能到達該處的案例
- 未覆蓋的非同步路徑:測試 resolved 和 rejected 的 Promise 分支
- 未覆蓋的錯誤處理:測試錯誤回呼、catch 區塊、錯誤邊界
使用偵測到的測試執行器模式:
- Vitest:
vi.mock()、vi.spyOn()、vi.fn() - Jest:
jest.mock()、jest.spyOn()、jest.fn() - react-scripts:與 Jest 相同
階段 7:驗證
在新增/更新測試後重新執行覆蓋率:
# 使用偵測到的指令
npx vitest --coverage # 適用於 Vitest
npx jest --coverage # 適用於 Jest
確認所有檔案在陳述式、分支、函式與行數上都達到 100%。
階段 8:重複
如果覆蓋率仍低於 100%,則回到階段 6。
各執行器設定
Vitest 覆蓋率設定
確保 vitest.config.ts:
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
exclude: [
'**/node_modules/**',
'**/dist/**',
'**/*.config.*',
'**/*.d.ts',
],
},
},
})
Jest 覆蓋率設定
確保 jest.config.ts 包含:
export default {
collectCoverage: true,
coverageReporters: ['text', 'json', 'html'],
collectCoverageFrom: [
'src/**/*.{ts,tsx,js,jsx}',
'!src/**/*.d.ts',
'!src/**/*.test.*',
'!src/**/*.spec.*',
],
}
提示
- 從已有測試但覆蓋率低的檔案開始 — 最快的勝利
- 然後處理最簡單邏輯的未測試檔案
- 對於 React 元件:測試渲染、使用者互動、條件渲染、錯誤狀態以及空/載入狀態
- 對於工具函式:測試邊界案例(空字串、null/undefined、邊界值、特殊字元)
- 對於 API 服務:測試成功回應、錯誤回應、載入狀態、逾時與網路失敗
- 如果發現無法涵蓋的死碼,建議移除或加上覆蓋率忽略註解:
- Vitest/V8:
/* c8 ignore next */或/* c8 ignore next 3 */ - Jest/Istanbul:
/* istanbul ignore next */或/* istanbul ignore if */
- Vitest/V8:
- 不要修改原始碼邏輯 — 僅新增或更新測試
- 遵循專案現有的測試模式(檔案命名、資料夾結構、mock 風格)
- 對於 0 個測試的檔案,先建立一個涵蓋所有主要路徑的全面測試檔,然後迭代
偵測優先順序
掃描原始檔時,依此順序檢查常見的目錄結構:
src/app/(Next.js app 目錄)components/lib/utils/server/(Next.js/Node.js)pages/(Next.js pages 目錄)- 根層級的
*.ts/*.tsx檔案
範例
使用者:「覆蓋率報告顯示 login.ts 為 72%,修復它」
代理動作:
- 執行
npx vitest --coverage --reporter=verbose,看到 login.ts 有未覆蓋的行 45-52(validateEmail的錯誤分支) - 讀取原始碼,了解
validateEmail在無效電子郵件時拋出錯誤 - 在
login.test.ts中為無效電子郵件輸入新增測試案例 - 重新執行覆蓋率 — login.ts 現在為 100%
使用者:「我們使用 jest,檢查覆蓋率」
- 執行
npx jest --coverage --verbose,識別未覆蓋的檔案 - 發現
src/components/Header.tsx為 0% — 無測試存在 - 讀取 Header.tsx 原始碼,建立
src/components/Header.test.tsx - 再次執行覆蓋率 — Header.tsx 現在為 100%
使用者:「這個專案沒有測試設定,加入覆蓋率」
- 在 package.json 中未偵測到測試執行器
- 詢問使用者:「未偵測到測試框架。要安裝 Vitest 嗎?(推薦)」
- 使用者確認 → 安裝 vitest + @vitest/coverage-v8,建立 vitest.config.ts
- 掃描 src/,找到 8 個原始檔,0 個測試檔
- 為所有 8 個檔案撰寫測試
- 執行覆蓋率 — 全部達到 100%