Jest 常用 API 速查表
一、测试用例组织
| API | 作用 | 示例 |
|---|---|---|
describe(name, fn) | 分组测试用例(测试套件) | describe('计算器测试', () => { ... }) |
test(name, fn, timeout) | 定义单个测试用例(别名 it) | test('1+1=2', () => { expect(1+1).toBe(2) }) |
test.only(name, fn) | 仅运行当前测试用例 | test.only('只测这个', () => { ... }) |
test.skip(name, fn) | 跳过当前测试用例 | test.skip('跳过这个', () => { ... }) |
二、断言匹配器(expect(value) 相关)
基础匹配器
| API | 作用 | 示例 |
|---|---|---|
toBe(value) | 严格相等(===) | expect(2).toBe(2) |
toEqual(value) | 深相等(对象/数组) | expect({a: 1}).toEqual({a: 1}) |
toBeTruthy() | 真值判断(非 null/0/'' 等) | expect(1).toBeTruthy() |
toBeFalsy() | 假值判断 | expect(0).toBeFalsy() |
toBeNull() | 为 null | expect(null).toBeNull() |
toBeUndefined() | 为 undefined | expect(undefined).toBeUndefined() |
数字/字符串匹配器
| API | 作用 | 示例 |
|---|---|---|
toBeGreaterThan(num) | 大于 | expect(3).toBeGreaterThan(2) |
toBeLessThan(num) | 小于 | expect(1).toBeLessThan(2) |
toContain(str) | 字符串包含 | expect('hello').toContain('ll') |
toMatch(regexp) | 正则匹配 | expect('123-456').toMatch(/\d{3}-\d{3}/) |
数组/集合匹配器
| API | 作用 | 示例 |
|---|---|---|
toContain(item) | 数组包含元素 | expect([1,2]).toContain(1) |
toEqual(expect.arrayContaining(arr)) | 数组包含指定子集 | expect([1,2,3]).toEqual(expect.arrayContaining([1,2])) |
异常匹配器
| API | 作用 | 示例 |
|---|---|---|
toThrow(error) | 函数抛出异常 | expect(() => { throw new Error() }).toThrow() |
三、测试钩子(生命周期)
| API | 作用 | 示例 |
|---|---|---|
beforeAll(fn) | 所有测试用例执行前运行一次 | beforeAll(() => { 初始化资源 }) |
afterAll(fn) | 所有测试用例执行后运行一次 | afterAll(() => { 释放资源 }) |
beforeEach(fn) | 每个测试用例执行前运行 | beforeEach(() => { 重置状态 }) |
afterEach(fn) | 每个测试用例执行后运行 | afterEach(() => { 清理数据 }) |
四、函数模拟(Mock)
| API | 作用 | 示例 |
|---|---|---|
jest.fn(implementation) | 创建模拟函数 | const mockFn = jest.fn(() => 42) |
mockFn.mock.calls | 获取函数调用参数列表 | expect(mockFn.mock.calls[0]).toEqual([1, 2]) |
mockFn.mock.results | 获取函数返回结果列表 | expect(mockFn.mock.results[0].value).toBe(42) |
mockFn.mockImplementation(fn) | 重写模拟函数实现 | mockFn.mockImplementation(() => 100) |
mockFn.mockReturnValue(value) | 模拟函数返回值 | mockFn.mockReturnValue('hello') |
mockFn.mockResolvedValue(value) | 模拟异步函数成功返回 | mockFn.mockResolvedValue({ code: 200 }) |
mockFn.mockRejectedValue(error) | 模拟异步函数失败返回 | mockFn.mockRejectedValue(new Error('失败')) |
五、模块模拟
| API | 作用 | 示例 |
|---|---|---|
jest.mock(modulePath) | 自动模拟整个模块 | jest.mock('./api') |
jest.spyOn(object, methodName) | 监视对象方法(可还原) | const spy = jest.spyOn(Math, 'random') |
jest.unmock(modulePath) | 取消模块模拟 | jest.unmock('./api') |
jest.doMock(modulePath, factory) | 动态模拟模块(不受 hoist 影响) | jest.doMock('./utils', () => ({ add: () => 3 })) |
六、定时器模拟
| API | 作用 | 示例 |
|---|---|---|
jest.useFakeTimers() | 使用假定时器 | jest.useFakeTimers() |
jest.runAllTimers() | 执行所有待处理定时器 | jest.runAllTimers() |
jest.runOnlyPendingTimers() | 执行当前待处理定时器 | jest.runOnlyPendingTimers() |
jest.advanceTimersByTime(ms) | 快进指定毫秒数 | jest.advanceTimersByTime(1000) |
jest.useRealTimers() | 恢复真实定时器 | jest.useRealTimers() |
七、快照测试
| API | 作用 | 示例 |
|---|---|---|
toMatchSnapshot() | 匹配快照(自动生成/更新) | expect(component.html()).toMatchSnapshot() |
toMatchInlineSnapshot() | 匹配内联快照(直接写在测试代码中) | expect(1+1).toMatchInlineSnapshot('2') |
八、其他常用 API
| API | 作用 | 示例 |
|---|---|---|
jest.setTimeout(timeout) | 设置测试超时时间(毫秒) | jest.setTimeout(10000) |
jest.clearAllMocks() | 清除所有模拟函数的调用记录 | jest.clearAllMocks() |
jest.resetAllMocks() | 重置所有模拟函数(保留实现) | jest.resetAllMocks() |
jest.isMockFunction(fn) | 判断是否为模拟函数 | expect(jest.isMockFunction(mockFn)).toBe(true) |