Jest Cheatsheet - Testing Framework

All essential Jest commands organized by use case, with 44+ entries you can copy and run directly. Find the right command fast when you need it.

Languages·44 commands·Last updated 2026-07-21
Back to Languages

Basic Testing 6

test("描述", () => { expect(1 + 2).toBe(3) })
定义一个Test用例
it("描述", fn)
test 的别名,BDD 风格更自然
describe("模块", () => { it(...) })
将相关Testgroup
test.skip("跳过", () => {})
临时Jump过此Test
test.only("聚焦", () => {})
只Run此Test(Debug用)
test.todo("待补充")
占位待实现的Test用例

Matchers 8

expect(value).toBe(other)
严格相(Object.is)
expect(obj).toEqual({ a: 1 })
深度相(recursivelycompare)
expect(arr).toHaveLength(3)
arrayorstringlength
expect(str).toMatch(/regex/)
正则Matchstring
expect(arr).toContain(item)
arraypackage含某元素
expect(value).toBeTruthy()
真值判断(反 toBeFalsy)
expect(fn).toThrow("error")
期望throwexception(可Match消息)
expect(value).toBeNull()
空值判断(另有 toBeUndefined/toBeDefined)

Async Testing 6

test("async", async () => { await fn() })
async/await 写法
test("promise", () => fn().then(d => expect(d).toBe(1)))
返回 Promise 让 Jest await
expect(promise).resolves.toBe(value)
断言 resolve 的值
expect(promise).rejects.toThrow("err")
断言 reject 的原因
test("done", done => { fn(done) })
done 回调写法(需手动call)
jest.useFakeTimers()
使用假scheduled器(配合 jest.runAllTimers())

Hooks 4

beforeEach(() => setup())
每个Test前Execute
afterEach(() => cleanup())
每个Test后Execute
beforeAll(() => init())
所有Test前Execute一次
afterAll(() => teardown())
所有Test后Execute一次

Mock Functions 8

const fn = jest.fn()
Create Mock function
jest.fn().mockReturnValue(42)
Set固定return value
jest.fn().mockResolvedValue(val)
返回 resolve 的 Promise
jest.fn().mockImplementation(n => n * 2)
自定义实现逻辑
jest.spyOn(obj, "method")
spy objectmethod(默认保留原实现)
jest.mock("./module")
自动 Mock 整个module的所有Export
jest.requireActual("./module")
在 Mock 上下文中引入真实module
fn.mockClear() / mockReset() / mockRestore()
清理call记录&实现

Assertions & Call Verification 5

expect(fn).toHaveBeenCalled()
验证function被call过
expect(fn).toHaveBeenCalledWith(arg)
验证callOptions
expect(fn).toHaveBeenCalledTimes(2)
验证call次数
expect(fn).toHaveBeenLastCalledWith(arg)
验证最后一次callOptions
expect(obj).toMatchObject({ a: 1 })
object部分Match

Snapshot Testing & CLI 7

expect(tree).toMatchSnapshot()
Create/对比snapshot(Update加 -u)
expect(obj).toMatchInlineSnapshot()
内联snapshot(WriteTestFile)
expect(value).toBeInstanceOf(Class)
实例type断言
npx jest --coverage
生成overwrite率报告
npx jest --watch
监听改动重跑相关Test(--watchAll 全部)
npx jest --bail
首个失败立即Stop
npx jest -t "用例名"
按用例名正则FilterRun

💡 Tips

  • jest --coverage 生成覆盖率报告,--watch 开启监听模式。
  • jest.mock() 会自动 Mock 模块的所有导出,返回 jest.fn()。
  • toMatchSnapshot() 适合 UI 组件和序列化结构测试,更新快照加 -u 参数。
  • jest.spyOn(obj, "method") 可以 spy 对象方法而不完全 Mock。
  • useFakeTimers() 配合 runAllTimers() 可同步测试定时器相关逻辑。
  • test.only 调试完记得删除,否则会跳过其他测试用例。

Official References

Commands are compiled from the official docs below. Click to verify the latest usage.

Maintained by LaoHand

Publicly updated on Jul 21, 2026, continuously proofread against official docs.

Found an error? Report it

Wrong command or description? Open an issue to help us fix it.

Found an error? Report it