Jest

作者 mindrally97184105b5da無授權條款269 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫5 週前更新

Jest testing best practices for JavaScript and TypeScript applications, covering test structure, mocking, and assertion patterns.

AI 產生的概覽

針對 JavaScript 與 TypeScript 的 Jest 測試最佳實務,涵蓋測試結構、模擬、斷言、非同步測試與覆蓋率。

功能
為在 JavaScript 與 TypeScript 專案中撰寫 Jest 測試提供指引。內容涵蓋使用 describe 區塊與 Arrange-Act-Assert 模式的測試結構、setup 與 teardown 鉤子、使用 jest.mock、jest.fn 與 jest.spyOn 進行模擬、斷言匹配器的選擇、非同步測試、覆蓋率目標以及一般最佳實務。也包含針對 fetchUser 函式的範例測試模式,展示成功與失敗兩種情況。
適用情境
適用於撰寫、審查或改善 JavaScript 或 TypeScript 程式碼的 Jest 測試套件時。適合回答關於測試組織、模擬策略、斷言選擇、非同步測試處理或覆蓋率預期的問題。
執行需求
不附帶指令碼或工具,僅為說明性內容。使用這些指引通常假設已有安裝 Jest 的 JavaScript 或 TypeScript 專案,但不需要憑證或網路存取。

Jest Testing Best Practices

You are an expert in JavaScript, TypeScript, and Jest testing.

Core Principles

Test Structure

  • Use descriptive test names that clearly explain expected behavior
  • Organize tests using describe blocks for logical grouping
  • Follow the Arrange-Act-Assert (AAA) pattern in each test
  • Keep tests focused on a single behavior or outcome

Setup and Teardown

  • Use beforeEach and afterEach for test isolation
  • Use beforeAll and afterAll for expensive setup that can be shared
  • Clean up any side effects in teardown hooks

Mocking

  • Use jest.mock() for module mocking
  • Use jest.fn() for function mocks
  • Use jest.spyOn() when you need to track calls but keep implementation
  • Clear mocks between tests with jest.clearAllMocks()
  • Avoid over-mocking: test real behavior when feasible

Assertions

  • Use the most specific matcher available
  • Prefer toEqual for object comparison, toBe for primitives
  • Use toMatchSnapshot sparingly and with meaningful names
  • Include negative test cases (what should NOT happen)

Async Testing

  • Always return promises or use async/await in async tests
  • Use waitFor from testing libraries for async assertions
  • Set appropriate timeouts for long-running tests

Coverage

  • Aim for meaningful coverage, not just high percentages
  • Test edge cases and error conditions
  • Use --coverage flag to track coverage metrics

Best Practices

  • Keep tests DRY but readable (prefer clarity over brevity)
  • Test behavior, not implementation details
  • Make tests deterministic (no random data without seeding)
  • Use factories or builders for test data creation

Example Patterns

javascript
describe('fetchUser', () => {  it('should return user data when API call succeeds', async () => {    const mockUser = { id: 1, name: 'John' };    jest.spyOn(api, 'get').mockResolvedValue(mockUser);
    const result = await fetchUser(1);
    expect(result).toEqual(mockUser);    expect(api.get).toHaveBeenCalledWith('/users/1');  });
  it('should throw error when API call fails', async () => {    jest.spyOn(api, 'get').mockRejectedValue(new Error('Not found'));
    await expect(fetchUser(999)).rejects.toThrow('Not found');  });});

來源與署名

來源:mindrally/skills位於jest提交9718410

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架