javascript-typescript-jest

javascript-typescript-jest

热门

使用 Jest 编写 JavaScript/TypeScript 测试的最佳实践,包括模拟策略、测试结构和常见模式。

3.6万Star
0Fork
更新于 2026/7/10
SKILL.md
readonly只读
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)