Jest Cheatsheet - Testing Framework
Jest 是 Facebook 出品的 JavaScript 测试框架,零配置开箱即用。最常用的 API 都在这里了,快速编写测试。
Back to Languages基础测试 6
test("描述", () => { expect(1 + 2).toBe(3) })定义一个测试用例
it("描述", fn)test 的别名,BDD 风格更自然
describe("模块", () => { it(...) })将相关测试分组
test.skip("跳过", () => {})临时跳过此测试
test.only("聚焦", () => {})只运行此测试(调试用)
test.todo("待补充")占位待实现的测试用例
匹配器 Matchers 8
expect(value).toBe(other)严格相等(Object.is)
expect(obj).toEqual({ a: 1 })深度相等(递归比较)
expect(arr).toHaveLength(3)数组或字符串长度
expect(str).toMatch(/regex/)正则匹配字符串
expect(arr).toContain(item)数组包含某元素
expect(value).toBeTruthy()真值判断(反之 toBeFalsy)
expect(fn).toThrow("error")期望抛出异常(可匹配消息)
expect(value).toBeNull()空值判断(另有 toBeUndefined/toBeDefined)
异步测试 6
test("async", async () => { await fn() })async/await 写法
test("promise", () => fn().then(d => expect(d).toBe(1)))返回 Promise 让 Jest 等待
expect(promise).resolves.toBe(value)断言 resolve 的值
expect(promise).rejects.toThrow("err")断言 reject 的原因
test("done", done => { fn(done) })done 回调写法(需手动调用)
jest.useFakeTimers()使用假定时器(配合 jest.runAllTimers())
钩子函数 Hooks 4
beforeEach(() => setup())每个测试前执行
afterEach(() => cleanup())每个测试后执行
beforeAll(() => init())所有测试前执行一次
afterAll(() => teardown())所有测试后执行一次
Mock 函数 8
const fn = jest.fn()创建 Mock 函数
jest.fn().mockReturnValue(42)设置固定返回值
jest.fn().mockResolvedValue(val)返回 resolve 的 Promise
jest.fn().mockImplementation(n => n * 2)自定义实现逻辑
jest.spyOn(obj, "method")spy 对象方法(默认保留原实现)
jest.mock("./module")自动 Mock 整个模块的所有导出
jest.requireActual("./module")在 Mock 上下文中引入真实模块
fn.mockClear() / mockReset() / mockRestore()清理调用记录与实现
断言与调用验证 5
expect(fn).toHaveBeenCalled()验证函数被调用过
expect(fn).toHaveBeenCalledWith(arg)验证调用参数
expect(fn).toHaveBeenCalledTimes(2)验证调用次数
expect(fn).toHaveBeenLastCalledWith(arg)验证最后一次调用参数
expect(obj).toMatchObject({ a: 1 })对象部分匹配
快照测试与 CLI 7
expect(tree).toMatchSnapshot()创建/对比快照(更新加 -u)
expect(obj).toMatchInlineSnapshot()内联快照(写入测试文件)
expect(value).toBeInstanceOf(Class)实例类型断言
npx jest --coverage生成覆盖率报告
npx jest --watch监听改动重跑相关测试(--watchAll 全部)
npx jest --bail首个失败立即停止
npx jest -t "用例名"按用例名正则过滤运行
💡 Tips
- jest --coverage 生成覆盖率报告,--watch 开启监听模式。
- jest.mock() 会自动 Mock 模块的所有导出,返回 jest.fn()。
- toMatchSnapshot() 适合 UI 组件和序列化结构测试,更新快照加 -u 参数。
- jest.spyOn(obj, "method") 可以 spy 对象方法而不完全 Mock。
- useFakeTimers() 配合 runAllTimers() 可同步测试定时器相关逻辑。
- test.only 调试完记得删除,否则会跳过其他测试用例。