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 从公开仓库中收录这些内容。

举报或申请下架