Skip to content

Jest 常用 API 速查表

一、测试用例组织

API作用示例
describe(name, fn)分组测试用例(测试套件)describe('计算器测试', () => { ... })
test(name, fn, timeout)定义单个测试用例(别名 ittest('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()为 nullexpect(null).toBeNull()
toBeUndefined()为 undefinedexpect(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)

Released under the MIT License.