| | |

Jest 30 ๐Ÿƒ Cheatsheet

โฑ๏ธ Estimated read: 6 min | |

Version facts

ItemValue
ReleasedJune 2025
Node floor18, 20, 22+ (14, 16, 19, 21 dropped)
Config filejest.config.ts loads natively, no ts-node
DOM environmentjest-environment-jsdom, separate package
Test runnerjest-circus (only option since 28)
CLI flag--testPathPatterns (plural, repeatable)
Mock genericjest.fn<Fn>(), single function type

CLI flags

FlagPurpose
jestRun all tests
jest --watchRe-run on file change
jest --watchAllRe-run all on any change
jest --ciCI mode, fail on new snapshots
jest -uUpdate snapshots
jest --coverageCollect coverage
jest --onlyChangedTests affected by git changes
jest --onlyFailuresRe-run last failures
jest --listTestsPrint file selection, run nothing
jest --showConfigPrint resolved config
jest -t "name"Filter by test name
jest --shard=1/4Run one shard of four
jest --testPathPatterns=src/cartSelect by path
jest --maxWorkers=4Cap worker processes
jest --silentSuppress console output
jest --verbosePer-test output
# multiple patterns, no regex alternation
npx jest --testPathPatterns=src/cart --testPathPatterns=src/orders

# verify the selection before running
npx jest --listTests --testPathPatterns=src/cart

Config file

// jest.config.ts โ€” loaded natively in Jest 30
import type { Config } from 'jest';

const config: Config = {
  testEnvironment: 'jsdom',
  testEnvironmentOptions: { url: 'http://localhost:3000/' },
  testPathPatterns: ['src/**/*.test.tsx'],
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
  moduleNameMapper: { '\\.(css|scss)$': 'identity-obj-proxy' },
  transform: { '^.+\\.tsx?$': 'ts-jest' },
  coverageThreshold: { global: { branches: 80, lines: 85 } },
  maxWorkers: '50%',
};

export default config;
KeyPurpose
testEnvironmentnode, jsdom, or a package name
testEnvironmentOptionsConstructor options (url, pretendToBeVisual)
testPathPatternsArray of path patterns (was a string)
testPathIgnorePatternsArray of exclusions (unchanged)
setupFilesAfterEnvRuns after the framework is installed
setupFilesRuns before the framework
moduleNameMapperRegex โ†’ module path, for assets and aliases
transformFile pattern โ†’ transformer
transformIgnorePatternsPackages the transform skips
coverageThresholdFail below these percentages
maxWorkersWorker count, "50%" accepted
projectsMultiple configs in one run
snapshotFormatSerializer options
globalsProject-wide globalThis values

Matchers

MatcherAsserts
toBe(v)Object.is identity
toEqual(v)Deep equality, ignores undefined
toStrictEqual(v)Deep equality including undefined and types
toMatchObject(v)Subset match
toBeTruthy() / toBeFalsy()Truthiness
toBeNull() / toBeUndefined()null / undefined
toBeDefined()Not undefined
toContain(item)Array or string contains
toHaveLength(n).length
toMatch(regex)String match
toBeCloseTo(n, digits)Floating point
toBeGreaterThan(n)Numeric compare
toThrow(msg?)Throws
toThrowError(Type)Throws a specific type
toBeCalledWith(...)Mock received args
toHaveBeenCalledTimes(n)Call count
toHaveReturnedWith(v)Return value
toMatchSnapshot()Snapshot equality
toMatchInlineSnapshot()Inline snapshot
toHaveProperty(path, v)Nested property
resolves / rejectsPromise unwrap
expect(fn).toHaveBeenCalledTimes(2);
await expect(fetchUser(1)).resolves.toMatchObject({ name: 'Alice' });
await expect(fn()).rejects.toThrow('invalid');

Mock functions

// 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'));
APIPurpose
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' });
APIPurpose
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();

Timers

APIPurpose
jest.useFakeTimers()Freeze time
jest.useRealTimers()Restore the real clock
jest.advanceTimersByTime(ms)Move the clock forward
jest.runAllTimers()Run everything due
jest.runOnlyPendingTimers()Run only what is due now
jest.setSystemTime(date)Set the wall clock
jest.getRealSystemTime()The real clock
jest.clearAllTimers()Drop queued timers
beforeEach(() => jest.useFakeTimers());
afterEach(() => jest.useRealTimers());

test('debounces', () => {
  jest.setSystemTime(new Date('2025-01-01'));
  schedule(() => tick());
  jest.advanceTimersByTime(300);          // clear the debounce window
  expect(tick).toHaveBeenCalledTimes(1);
});

Snapshots

APIPurpose
toMatchSnapshot()Write or compare
toMatchInlineSnapshot(str?)Inline in the test file
jest --ciFail on new snapshots
jest -uUpdate every affected snapshot
jest -u --testPathPatterns=xUpdate a subset
expect.addSnapshotSerializer(s)Custom format
// 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();

Environments

EnvironmentPackageGlobals
nodejest-environment-nodeprocess, Buffer, no DOM
jsdomjest-environment-jsdomwindow, document, history
happy-dom@happy-dom/jest-environmentSame shape, faster
// per-file override
/** @jest-environment jsdom
 *  @jest-environment-options {"url": "https://shop.example.com/cart"} */
// what jsdom lacks โ€” polyfill once, in setupFilesAfterEnv
Object.defineProperty(window, 'matchMedia', {
  writable: true,
  value: (q: string) => ({ matches: false, media: q, addListener: jest.fn(),
                           removeListener: jest.fn(), addEventListener: jest.fn(),
                           removeEventListener: jest.fn(), dispatchEvent: jest.fn() }),
});
Element.prototype.scrollIntoView = jest.fn();
global.ResizeObserver = jest.fn(() => ({ observe: jest.fn(), unobserve: jest.fn(), disconnect: jest.fn() }));
// 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';
ItemValue
Config filejest.config.ts, no ts-node
Matcher types@types/jest, OR @jest/globals
Never bothTwo definitions, one wins silently
Mock typejest.MockedFunction<typeof fn>
Whole modulejest.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

Surface2930
CLI flag--testPathPattern--testPathPatterns
Config keytestPathPattern: stringtestPathPatterns: string[]
Mock genericjest.fn<R, A>()jest.fn<Fn>()
Config filets-node requirednative
Node floor14, 16, 18, 19, 20, 2118, 20, 22+
Environment packagebundled before 28jest-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

RemovedReplacement
jest.addMatchersexpect.extend
jest.resetModuleRegistryjest.resetModules
jest.runTimersToTimejest.advanceTimersByTime
jest.genMockFromModulejest.createMockFromModule
require.requireActualjest.requireActual
testURL (config)testEnvironmentOptions.url
jasmine2 (runner)jest-circus

Common pitfalls

SymptomCauseFix
document is not definedEnvironment is nodetestEnvironment: 'jsdom'
No tests foundSingular flag in a script--testPathPatterns
Cannot redefine property: locationUnforgeable bindinghistory.pushState
Generic arity errorjest.fn<R, A>()One function type
Environment not resolvablePackage not installednpm i -D jest-environment-jsdom
Runner fails at startupOld Node in CIPin an even LTS
Mock typed as anyCast to silencejest.MockedFunction
Two type definitionsBoth packages activeOne in tsconfig
getBoundingClientRect all zerosNo layout in jsdomAssert on text or role
Previous test’s markup foundShared document per filedocument.body.innerHTML = ''
Test hangs with fake timersuserEvent frozenadvanceTimers 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
window.history.pushState({}, '', '/cart');            // โœ… change the URL
delete window.location;                               // โŒ spec-forbidden

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!