SKILL.md
readonlyread-only
name
javascript-typescript-jest
description
使用 Jest 撰寫 JavaScript/TypeScript 測試的最佳實務,包含模擬策略、測試結構與常見模式。
測試結構
- 測試檔案命名以
.test.ts或.test.js結尾 - 測試檔案放在被測程式碼旁或專屬的
__tests__目錄中 - 使用描述性的測試名稱來說明預期行為
- 使用巢狀 describe 區塊來組織相關測試
- 遵循模式:
describe('Component/Function/Class', () => { it('should do something', () => {}) })
有效模擬
- 模擬外部相依(API、資料庫等)以隔離測試
- 使用
jest.mock()進行模組層級的模擬 - 使用
jest.spyOn()進行特定函式的模擬 - 使用
mockImplementation()或mockReturnValue()定義模擬行為 - 在
afterEach中使用jest.resetAllMocks()重置各測試間的模擬
測試非同步程式碼
- 在測試中務必回傳 Promise 或使用 async/await 語法
- 對 Promise 使用
resolves/rejects匹配器 - 使用
jest.setTimeout()為較慢的測試設定適當逾時
快照測試
- 對 UI 元件或變動不頻繁的複雜物件使用快照測試
- 保持快照小而專注
- 提交前仔細審查快照變更
測試 React 元件
- 優先使用 React Testing Library 而非 Enzyme 測試元件
- 測試使用者行為與元件可及性
- 透過可及性角色、標籤或文字內容查詢元素
- 使用
userEvent而非fireEvent以模擬更真實的使用者互動
常見 Jest 匹配器
- 基本:
expect(value).toBe(expected)、expect(value).toEqual(expected) - 真值:
expect(value).toBeTruthy()、expect(value).toBeFalsy() - 數字:
expect(value).toBeGreaterThan(3)、expect(value).toBeLessThanOrEqual(3) - 字串:
expect(value).toMatch(/pattern/)、expect(value).toContain('substring') - 陣列:
expect(array).toContain(item)、expect(array).toHaveLength(3) - 物件:
expect(object).toHaveProperty('key', value) - 例外:
expect(fn).toThrow()、expect(fn).toThrow(Error) - 模擬函式:
expect(mockFn).toHaveBeenCalled()、expect(mockFn).toHaveBeenCalledWith(arg1, arg2)






