Testing

Jest

A testing framework for JavaScript and TypeScript: runner, assertions, mocks and coverage in one package.

What it is

Facebook (Meta) created Jest in 2014, and today the project belongs to the OpenJS Foundation. It bundles everything for unit tests: running, expect assertions, mocks, timers, snapshot tests and coverage reports.

Tests run in parallel in isolated workers, and watch mode reruns only changed tests. jsdom provides a DOM, and for React you add React Testing Library.

Jest was the standard in the JS world for a long time. New Vite projects more often pick Vitest, but in many existing codebases (including React Native) Jest remains the default.

Use it when

  • Unit and integration tests of JS / TS code.
  • React Native or an existing project where Jest is already set up.
  • You need snapshot tests and built-in coverage without extra packages.

Avoid it when

  • A new Vite project with ES modules: Vitest is simpler to configure.
  • End-to-end browser tests: use Playwright or Cypress.

Key concepts

describe / it / expect
Test groups, individual tests and result assertions.
Mocks
jest.fn() and jest.mock() replace functions and modules.
Snapshot
Saves output and compares against it in later runs.
Fake timers
Control of setTimeout and Date in tests.
Coverage
A report of which lines and branches ran.

Example

A simple test and a jest.fn() spy.

Interview questions

  1. 1. How does jest.fn() differ from jest.mock()?

    jest.fn() creates a mock function whose calls you can watch. jest.mock('module') replaces a whole module with a mock within the test.

  2. 2. What is a snapshot test and when does it hurt?

    A test compares output against a saved snapshot. It is quick to write, but nobody reads big snapshots and they just get updated. So keep them small and targeted.

  3. 3. How do you test async code?

    Return a promise or use async / await and expect(...).resolves or rejects. Fake timers handle timers.

  4. 4. Why isolate tests?

    Each test file runs in its own context, so one test's global state does not affect another and parallel runs are safe.

Interview questions from the bank

Comparisons with this technology

Logos belong to their owners and are used for identification only. Icons: Simple Icons (CC0), Devicon (MIT).