100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Testing

Jest Quick Reference

A condensed cheat sheet of essential Jest CLI flags, matchers, lifecycle hooks, and config keys for day-to-day use.

Practical JestBeginner8 min readJul 10, 2026
Analogies

Essential CLI Flags

The most-used Jest CLI flags cover everyday workflows: --watch reruns only tests related to changed files interactively, -t "pattern" filters to tests whose name matches a regex, --coverage generates a coverage report, and --ci switches to non-interactive mode suited for pipelines. Combining -t with a specific test file path, like jest userService -t "handles errors", narrows execution to a fast, focused subset during debugging.

🏏

Cricket analogy: The -t flag filtering tests by name is like a broadcaster searching match footage for every delivery bowled to a specific batter, ignoring the rest of the innings entirely.

Common Matchers Cheat Sheet

Equality matchers split by intent: toBe for primitive/reference equality, toEqual for deep value equality, and toStrictEqual which additionally checks for undefined properties and object type (e.g. distinguishing a class instance from a plain object). Truthiness matchers include toBeNull, toBeUndefined, toBeDefined, toBeTruthy, and toBeFalsy, while numeric matchers include toBeGreaterThan, toBeLessThanOrEqual, and toBeCloseTo for floating-point comparisons; array/object matchers include toContain, toHaveLength, and toHaveProperty.

🏏

Cricket analogy: toStrictEqual catching a type mismatch is like a scorer flagging that a declared innings total technically differs from a forfeited one, even if the printed run count looks the same.

Async and promise matchers combine with await: await expect(promise).resolves.toBe(value) and await expect(promise).rejects.toThrow(errorOrMessage) both automatically unwrap the promise before asserting. For mock functions, toHaveBeenCalled, toHaveBeenCalledTimes(n), toHaveBeenCalledWith(...args), and toHaveBeenLastCalledWith(...args) verify a jest.fn() or jest.spyOn() was invoked correctly.

🏏

Cricket analogy: await expect(promise).resolves.toBe is like waiting for a DRS review to actually finish processing before reading out the confirmed decision, rather than guessing mid-review.

Lifecycle Hooks and Key Config Options

The four lifecycle hooks run in a predictable order: beforeAll runs once before all tests in a file or describe block, beforeEach runs before every individual test, afterEach runs after every test, and afterAll runs once after all tests complete, with each accepting an optional scope when placed inside a nested describe. Key jest.config.js options include testEnvironment (node vs jsdom), setupFilesAfterEach for global test setup like extending expect with jest-dom, collectCoverageFrom for controlling which source files count toward coverage, and moduleNameMapper for aliasing imports like @/components to a real path.

🏏

Cricket analogy: beforeAll running once per file is like a single toss deciding conditions for an entire Test match, while beforeEach resetting state is like re-marking the crease before every individual delivery.

javascript
// jest.config.js
module.exports = {
  testEnvironment: 'jsdom',
  setupFilesAfterEach: ['<rootDir>/jest.setup.js'],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
  },
  collectCoverageFrom: ['src/**/*.{js,ts,tsx}', '!src/**/*.d.ts'],
  coverageThreshold: {
    global: { branches: 80, functions: 80, lines: 80, statements: 80 },
  },
};

// example.test.js
describe('cart total', () => {
  beforeEach(() => { /* reset cart fixture */ });

  it('sums item prices', () => {
    expect(getTotal([{ price: 10 }, { price: 5 }])).toBe(15);
  });
});

Quick lookup: toBe (reference/primitive), toEqual (deep value), toStrictEqual (deep value + type + undefined props), toContain (array/string membership), toHaveLength (array/string length), resolves/rejects (async unwrap), toHaveBeenCalledWith (mock call args).

The config key is setupFilesAfterEnv in most Jest versions, not setupFilesAfterEach - double-check the exact key name against your installed Jest version's documentation, since a typo here silently fails to load global setup like jest-dom matchers without any error.

  • --watch, -t, --coverage, and --ci are the most common day-to-day CLI flags.
  • toBe checks reference/primitive equality; toEqual and toStrictEqual check deep value equality.
  • Numeric/array matchers include toBeGreaterThan, toBeCloseTo, toContain, and toHaveLength.
  • resolves/rejects automatically unwrap promises for async assertions.
  • toHaveBeenCalledWith verifies a mock's exact call arguments, not just that it was called.
  • beforeAll/afterAll run once per scope; beforeEach/afterEach run around every single test.
  • Key config keys: testEnvironment, setupFilesAfterEnv, moduleNameMapper, collectCoverageFrom, coverageThreshold.

Practice what you learned

Was this page helpful?

Topics covered

#Testing#JestStudyNotes#TestingQA#JestQuickReference#Jest#Quick#Reference#Essential#StudyNotes#SkillVeris