← Back to Jest Mastery
Basic18 min read

Jest Basics

Install Jest, write test files with describe and test, use expect assertions, and run your suite.

Installing and Configuring Jest

Add Jest as a dev dependency and configure it in jest.config.js or package.json. For TypeScript projects, use ts-jest or Babel presets to transform files before execution.

Jest zero-config works for many JavaScript projects out of the box. Explicit configuration helps when using path aliases, CSS modules, or non-standard file extensions.

  • Use testEnvironment: "jsdom" when testing browser APIs or React components
  • Add setupFilesAfterEnv for global test setup like @testing-library/jest-dom
  • Run tests with npx jest or npm test script
npm install --save-dev jest @types/jest ts-jest

// jest.config.ts
export default {
  preset: "ts-jest",
  testEnvironment: "node",
  roots: ["<rootDir>/src"],
  testMatch: ["**/*.test.ts"],
};

Test Structure

Organize tests with describe blocks grouping related cases and test (or it) defining individual examples. Nested describe blocks mirror module or feature hierarchy.

Each test should be independent—order of execution is not guaranteed. Avoid shared mutable state between tests unless reset in beforeEach hooks.

describe("calculateDiscount", () => {
  test("returns 10% off for premium members", () => {
    expect(calculateDiscount(100, "premium")).toBe(90);
  });

  test("returns full price for standard members", () => {
    expect(calculateDiscount(100, "standard")).toBe(100);
  });
});

Assertions with expect

expect wraps values and chains matchers like toBe, toEqual, and toThrow. toBe uses Object.is equality (good for primitives); toEqual deep-compares objects and arrays.

Use expect.assertions(n) in async tests to verify a specific number of assertions ran—catches tests that silently pass without executing expectations.

expect(2 + 2).toBe(4);
expect({ a: 1 }).toEqual({ a: 1 });
expect(() => parseJSON("invalid")).toThrow(SyntaxError);

Running Tests

Run the full suite with jest, filter by filename pattern with jest auth, or run a single file with jest path/to/file.test.ts. Watch mode re-runs affected tests on file changes.

CI pipelines should run jest --ci --coverage for deterministic output without watch and with coverage reports for gates.

  • --bail stops on first failure for faster CI feedback loops
  • --onlyFailures re-runs tests that failed in the previous run
  • Use --testNamePattern to filter by test description regex
{
  "scripts": {
    "test": "jest",
    "test:watch": "jest --watch",
    "test:ci": "jest --ci --coverage --maxWorkers=2"
  }
}

Project Layout Conventions

Co-locate tests as *.test.ts next to source or mirror structure in __tests__ directories. Keep test files focused—one module or component per file when possible.

Name tests after behavior, not implementation. "returns 404 when user not found" beats "calls findById".

  • Exclude test files from production bundles via tsconfig exclude
  • Share fixtures in __fixtures__ or test-utils folders
  • Avoid testing private functions directly—test public API behavior

Get In Touch


Ready to discuss your next project? Drop me a message.