# multiple patterns, no regex alternation
npx jest --testPathPatterns=src/cart --testPathPatterns=src/orders
# verify the selection before running
npx jest --listTests --testPathPatterns=src/cart
// inferred from the implementation
const save = jest.fn(async (id: string) => store.write(id));
// one function type
const notify = jest.fn<(to: string, body: string) => Promise<boolean>>();
// realistic values, set per test
notify.mockResolvedValue(true);
notify.mockRejectedValue(new Error('smtp down'));
API
Purpose
jest.fn(impl?)
New mock function
mockImplementation(fn)
Replace body
mockReturnValue(v)
Fixed return
mockResolvedValue(v)
Promise.resolve
mockRejectedValue(e)
Promise.reject
mockReturnValueOnce(v)
First call only
mockImplementationOnce(fn)
First call only
mockReset()
Clear calls and implementation
mockClear()
Clear calls only
mockRestore()
Restore the original
mock.calls
[args, ...] per call
mock.results
{ type, value } per call
Module mocking
// auto-mock everything a module exports
jest.mock('../api/users');
// factory form, with the originals available
jest.mock('../api/users', () => ({
...jest.requireActual('../api/users'),
fetchUser: jest.fn(),
}));
// typed handle to a mocked module function
import { fetchUser } from '../api/users';
const mocked = jest.mocked(fetchUser);
mocked.mockResolvedValue({ id: 1, name: 'Alice' });
API
Purpose
jest.mock(p)
Auto-mock
jest.mock(p, factory)
Custom mock
jest.requireActual(p)
Real module
jest.requireMock(p)
The mock
jest.unmock(p)
Undo
jest.doMock(p, f)
Non-hoisted mock
jest.mocked(fn)
Typed mock handle
jest.MockedFunction<T>
The variable type
jest.Mocked<T>
Whole module type
jest.spyOn(o, m)
Wrap a method
jest.restoreAllMocks()
Undo every spy
// spy on a method and assert it
const log = jest.spyOn(console, 'error').mockImplementation(() => {});
// ... trigger the code ...
expect(log).toHaveBeenCalledWith(expect.stringContaining('invalid'));
log.mockRestore();
// structural, not a whole-tree dump
expect(formatOrder(order)).toMatchInlineSnapshot(`
"Order #42: 3 items, $29.00"
`);
// the only snapshot worth writing: a formatted value, not a component tree
const serialize = (v: object) => JSON.stringify(v, Object.keys(v).sort(), 2);
expect(serialize({ id: 1, name: 'A' })).toMatchSnapshot();
// location is unforgeable โ change the URL, do not replace the binding
window.history.pushState({}, '', '/orders?page=2');
jest.spyOn(window.location, 'replace').mockImplementation(() => {});
TypeScript
// the global API
import type { Config } from 'jest';
// the module API, ESM-safe
import { jest, describe, test, expect, beforeEach } from '@jest/globals';
Item
Value
Config file
jest.config.ts, no ts-node
Matcher types
@types/jest, OR @jest/globals
Never both
Two definitions, one wins silently
Mock type
jest.MockedFunction<typeof fn>
Whole module
jest.Mocked<typeof mod>
DOM matchers
@testing-library/jest-dom in setupFilesAfterEnv
// tsconfig.json โ pick one source of truth
{ "compilerOptions": { "types": ["jest"] } }
Migration from Jest 29
Surface
29
30
CLI flag
--testPathPattern
--testPathPatterns
Config key
testPathPattern: string
testPathPatterns: string[]
Mock generic
jest.fn<R, A>()
jest.fn<Fn>()
Config file
ts-node required
native
Node floor
14, 16, 18, 19, 20, 21
18, 20, 22+
Environment package
bundled before 28
jest-environment-jsdom
// before
const save = jest.fn<Promise<void>, [string]>();
// after โ one function type
const save = jest.fn<(id: string) => Promise<void>>();
// best โ infer from the body
const save = jest.fn(async (id: string) => {});
# the verification that matters
npx jest --listTests --testPathPatterns=src/cart # empty means stale
npx tsc --noEmit # mocks compile
node -v # floor is met
npx jest --showConfig # resolved config
Long-gone aliases
Removed
Replacement
jest.addMatchers
expect.extend
jest.resetModuleRegistry
jest.resetModules
jest.runTimersToTime
jest.advanceTimersByTime
jest.genMockFromModule
jest.createMockFromModule
require.requireActual
jest.requireActual
testURL (config)
testEnvironmentOptions.url
jasmine2 (runner)
jest-circus
Common pitfalls
Symptom
Cause
Fix
document is not defined
Environment is node
testEnvironment: 'jsdom'
No tests found
Singular flag in a script
--testPathPatterns
Cannot redefine property: location
Unforgeable binding
history.pushState
Generic arity error
jest.fn<R, A>()
One function type
Environment not resolvable
Package not installed
npm i -D jest-environment-jsdom
Runner fails at startup
Old Node in CI
Pin an even LTS
Mock typed as any
Cast to silence
jest.MockedFunction
Two type definitions
Both packages active
One in tsconfig
getBoundingClientRect all zeros
No layout in jsdom
Assert on text or role
Previous test’s markup found
Shared document per file
document.body.innerHTML = ''
Test hangs with fake timers
userEvent frozen
advanceTimers option
Do / Don’t
jest.fn(async (id: string) => store.write(id)); // โ infer the type
jest.fn<(id: string) => Promise<void>>(); // โ when no body
jest.fn<Promise<void>, [string]>(); // โ old arity
jest.mocked(fetchUser); // โ typed handle
const save = jest.fn() as any; // โ silences the check
jest --testPathPatterns=src/cart # โ
jest --testPathPattern=src/cart # โ selects nothing
jest --listTests --testPathPatterns=src/cart # โ verify first
expect(screen.queryByRole('alert')).not.toBeInTheDocument(); // โ absence
expect(screen.getByRole('alert')).not.toBeInTheDocument(); // โ throws first