Jest and Vitest Cheat Sheet: Matchers, Mocks, Timers and CLI
Checked against Jest, Vitest Jest 30.5.2 and Vitest 5.1.2, both run locally on Node 24.4.0 on 28 November 2026. Each section links to the official docs it was checked against.
This sheet is for JavaScript and TypeScript developers who write unit tests in Jest or Vitest, or are moving from one to the other. It follows jestjs.io (Jest 30.5) and vitest.dev (Vitest 5.1). The examples were run with Jest 30.5.2 and Vitest 5.1.2 installed in a scratch project; rows checked only in the docs are marked untested.
When to use what
The APIs overlap so much that most rows below work in both with jest. swapped for vi.. The choice is about the rest of your stack. If you already build with Vite, Vitest reuses that config and transforms, so TypeScript and ESM need no extra setup. Jest is still the safe pick for a large existing suite, React Native, or a project whose tooling assumes it. Our post on choosing a test runner goes through the trade-offs, and testing React components with Vitest shows a full setup.
Three differences catch people. Vitest has no globals unless you enable them, so you import describe, it, expect and vi from vitest. A Vitest module mock factory must return an object of named exports, while Jest treats the factory's return value as the default export. And Vitest joins suite and test names with > , so -t patterns that span both need that separator.
Use the Jest matcher builder when you can't remember which matcher fits, and the test case generator to list edge cases before you write them.
Vitest's expect is compatible; see https://vitest.dev/api/expect.html.
expect(x).toBe(3)Strict identity with Object.is; right for numbers, strings and the same object reference
expect(obj).toEqual({ id: 1 })Deep equality that ignores properties set to undefined
expect(obj).toStrictEqual({ id: 1, tags: ['a'] })Deep equality that also checks undefined properties, sparse arrays and class types
expect(obj).toMatchObject({ id: 1 })Pass if the object contains these properties, ignoring extra ones
expect(0.1 + 0.2).toBeCloseTo(0.3)Compare floats without rounding errors failing the test
expect(res).toEqual(expect.objectContaining({ id: 1 }))Match part of a nested value inside a bigger assertion
expect(() => parse('')).toThrow('empty')Assert a function throws; wrap the call in a function or the error escapes first
await expect(promise).resolves.toEqual({ ok: true })Unwrap a promise and assert on its value; you must await or return it
await expect(promise).rejects.toThrow('down')Assert a promise rejects with a matching error
expect.assertions(2)Fail the test unless exactly two assertions ran, useful in async callbacks
Vitest equivalents use vi: https://vitest.dev/api/vi.html and https://vitest.dev/api/mock.html.
const fn = jest.fn() / vi.fn()Create a mock function that records calls and returns undefined
fn.mockResolvedValueOnce({ ok: true })Make the next call return a resolved promise; chain several Once calls for a sequence
fn.mockRejectedValueOnce(new Error('503'))Make the next call return a rejected promise
fn.mockImplementation((x) => x * 2)Give the mock a real body for every call
expect(fn).toHaveBeenCalledTimes(2)Assert how many times the mock ran
expect(spy).toHaveBeenCalledWith('careful')Assert at least one call had these arguments
jest.spyOn(console, 'warn').mockImplementation(() => {})Watch an existing method and silence it; call mockRestore() to put it back
jest.mock('./api') / vi.mock('./api', () => ({ get: vi.fn() }))Replace a module; Vitest's factory must return named exports
await vi.importActual('./api')Load the real module inside a partial mock; Jest's equivalent is jest.requireActual
jest.restoreAllMocks() / vi.restoreAllMocks()Undo every spy so later tests see the real methods
Hooks are described at https://jestjs.io/docs/setup-teardown. Vitest's migration guide says it does not support Jest's legacy timers.
jest.useFakeTimers() / vi.useFakeTimers()Replace setTimeout, setInterval and Date with controllable fakes
await vi.advanceTimersByTimeAsync(1000)Move fake time forward 1 s and let promises queued by those timers settle
await vi.runAllTimersAsync()Run every pending timer, including ones scheduled while running
vi.setSystemTime(new Date('2026-01-01'))Freeze Date.now() at a fixed moment while fake timers are on
jest.useRealTimers()Switch back to real timers, usually in afterEach
beforeEach(() => { ... })Run setup before every test in the file or describe block
afterAll(async () => { await db.close() })Clean up once after the last test, such as closing a connection
Vitest flags are at https://vitest.dev/guide/cli.html. Plain vitest watches in a terminal and runs once in CI.
expect(value).toMatchInlineSnapshot()Write the snapshot into the test file on first run; both tools filled it in here
expect(tree).toMatchSnapshot()Store the snapshot in a __snapshots__ file next to the test
jest -u / vitest -uRewrite snapshots that no longer match, after you have read the diff
jest -t 'retry spies'Run tests whose space-joined name matches; ran here, 1 passed and 2 skipped
vitest run -t 'retry > gives up'Run one test by its > -joined name; 'retry gives up' matched nothing in Vitest 5
vitest runRun once and exit, no watch mode
jest --watchWatch files and re-run tests related to what changed; --watchAll re-runs everything
jest --coverage / vitest run --coverageCollect a coverage report
jest --runInBandRun tests serially in one process, handy for debugging
vitest run --last-failedRe-run only the tests that failed last time
Worked example: Test a retry helper with fake timers in both runners
A retry(fn, times = 3, delayMs = 1000) helper waits one second between attempts. Real timers would make the test slow, so fake them and push time forward by hand. The Vitest version:
import { it, expect, vi, beforeEach, afterEach } from 'vitest'
import { retry } from './retry.js'
beforeEach(() => { vi.useFakeTimers() })
afterEach(() => { vi.useRealTimers() })
it('returns after a failure then a success', async () => {
const fn = vi.fn()
.mockRejectedValueOnce(new Error('503'))
.mockResolvedValueOnce({ ok: true })
const p = retry(fn)
await vi.advanceTimersByTimeAsync(1000)
await expect(p).resolves.toEqual({ ok: true })
expect(fn).toHaveBeenCalledTimes(2)
})
The first call rejects, retry schedules a one-second wait, and advanceTimersByTimeAsync(1000) fires that timer and flushes the promises behind it. The second call resolves, so the result is { ok: true } and the mock ran twice. Running npx vitest run printed Tests 4 passed (4) for the full file in 143 ms.
The Jest file is identical apart from the import line and jest. in place of vi.; npx jest reported Tests: 3 passed, 3 total. For the give-up case, attach expect(p).rejects.toThrow() before running the timers, then await it afterwards, or the rejection is reported as unhandled.
Common mistakes
Copying a Jest test into Vitest and getting "describe is not defined".
Import the test functions from
vitest, or setglobals: truein the Vitest config.Porting
jest.mock('./x', () => 'hello')straight tovi.mock.Return an object of exports from the factory, for example
({ default: 'hello' }).Forgetting to await
expect(p).resolvesor.rejects, so the test passes before the assertion runs.Always
awaitorreturnthese assertions.Relying on mock call counts that carry over from a
beforeAllin Vitest 5.Vitest 5 clears call history before each test; record calls inside the test or set
clearMocks: false.Running
-uto make a failing snapshot pass without reading the diff.Read the snapshot diff first and update only when the new output is what you want.
Related cheat sheets
Sources
- https://jestjs.io/docs/expect
- https://jestjs.io/docs/mock-function-api
- https://jestjs.io/docs/jest-object
- https://jestjs.io/docs/timer-mocks
- https://jestjs.io/docs/setup-teardown
- https://jestjs.io/docs/cli
- https://vitest.dev/guide/migration/jest
- https://vitest.dev/guide/migration.html
- https://vitest.dev/guide/cli.html
- https://vitest.dev/api/vi.html
- https://vitest.dev/api/mock.html
- https://github.com/vitest-dev/vitest/releases
How we research: where our facts come from, how often we re-check them, and why no one can pay for a review or a verdict.