Skip to content
Tutorials Center
My learning

Topics

Lesson 1 of 30 ยท Getting Started

What Is Jest?

Learn what Jest does, how a test runner, assertions and mocks fit together, how Jest compares with Vitest and node:test, and what happens when a test file runs.

Jest is a JavaScript testing framework. You write small programs, called tests, that call your code and check the result. Jest finds those tests, runs them, and tells you which ones passed and which ones failed, with a readable explanation for every failure.

Automated tests matter because code changes. Today a function returns the right price. Next month someone adds a discount rule, and the function quietly breaks for one edge case. A test suite notices that within seconds, long before a customer does. This lesson explains what Jest is made of, how it compares with other tools, and what happens when you run it.

Real versus stand-in. Jest is a Node.js program installed with npm, so it cannot run inside this page. The install commands, configuration and Jest test files in plain code blocks are real and read-only. The runnable examples are small stand-ins written in plain JavaScript that behave like the parts of Jest we are discussing. They are for understanding, not a copy of Jest's source.

Three jobs in one package

When people say "Jest", they usually mean three tools that ship together.

Jest does three jobs

Test runner Finds test files, runs them, reports results.
Assertions expect() checks that values are what you expect.
Mocking Replace real code with controllable fakes.

Other languages often split these jobs across separate libraries.

1 / 2
  • The runner discovers files, runs each test, catches failures and prints a report.
  • The assertion library gives you expect(value) followed by a matcher such as .toBe(3).
  • The mocking tools (jest.fn, jest.spyOn, jest.mock, fake timers) let you replace a slow or unpredictable dependency, such as a network call or the clock.

Many ecosystems make you pick and combine these yourself. Jest's selling point is that a new project needs one dev dependency and almost no setup.

Installing Jest

In a project that already has a package.json, you install Jest as a development dependency and add a script:

Terminal
npm install --save-dev jest
JSON
{
  "scripts": {
    "test": "jest"
  }
}

From then on, npm test runs every test file in the project. Jest 30, the current major version at the time of writing, needs a supported Node.js release; check the Jest documentation for the exact minimum if you use an older Node.

How Jest finds tests

By default Jest treats a file as a test file when it matches one of two patterns:

  • any file inside a folder named __tests__;
  • any file whose name ends in .test.js or .spec.js (also .ts, .jsx, .tsx and the .mjs/.cjs variants).

So sum.test.js next to sum.js is a test file, and sum.js is ordinary code. You can change these patterns with the testMatch option, which we cover in Configuring Jest.

What happens when a test file runs

Running a test file is not the same as running a normal script. Jest does the following for each test file:

flowchart LR
  A["Jest starts<br/>(finds test files)"] --> B["Worker process<br/>takes one file"]
  B --> C["Set up globals<br/>test, expect, jest"]
  C --> D["Run the file:<br/>test() calls register tests"]
  D --> E["Run each registered test<br/>in order"]
  E --> F["Send results<br/>back to Jest"]
  F --> G["Print the report"]

Registration comes first, execution second. Calling test() does not run anything yet; it only adds the test to a list.

Three details are worth remembering:

  1. Globals are injected. test, describe, expect and jest are available in every test file without an import. (You can import them from @jest/globals if you prefer explicit imports, which helps with TypeScript.)
  2. Each file is isolated. Every test file gets its own module registry, so a module you change in one file does not leak into another. Files may run in parallel in different workers.
  3. A test fails when it throws. If the function you passed to test() finishes without an exception, the test passes. A failed expect simply throws an error with a nice message.

The second point is why Jest suites scale well: files cannot interfere with each other, so Jest can run them at the same time.

A test runner in a few lines

The stand-in below is a miniature runner. It does the registration-then-execution dance, and treats a thrown error as a failure. Run it, then change 5 to 4 in the third test and run it again; the failure disappears.

JS A tiny test runner

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The real Jest adds a great deal around this loop: timing, workers, nicer messages, hooks, timeouts, async support. But the core idea is exactly this one.

Assertions and mocks, side by side

Assertions answer "is this value right?". Mocks answer "how was this function used?" and "what if this dependency behaved differently?". Here is the same pair of ideas as a stand-in. The expect below knows two matchers, and fn records its calls the way jest.fn() does.

JS An assertion and a mock in miniature

Press Run (or Ctrl + Enter) to see the console output here.

No output.

No real message was sent. The fake send captured its arguments, so the test could check them. That is the whole point of mocking, and we explore the real tools in Mock Functions with jest.fn.

Jest, Vitest and node:test

Jest is not the only choice. Here is an honest comparison.

Jest Vitest node:test
Comes from Meta, now an OpenJS Foundation project The Vite ecosystem Built into Node.js
Install needed Yes Yes No
API style describe/test/expect, globals Almost the same as Jest, globals optional describe/it with node:assert
Mocking Built in (jest.fn, jest.mock) Built in (vi.fn, vi.mock) mock helpers in node:test
Snapshots, coverage, watch Built in Built in Snapshots and coverage exist but are younger
Best fit Existing and Node/React projects, huge ecosystem Vite and ESM-first projects Small libraries wanting zero dependencies

The skills transfer well. If you can read a Jest test, you can read a Vitest test with only a handful of renames (jest.fn becomes vi.fn). Jest has the largest body of examples, answers and plugins, and many companies run it, which is why it is worth learning first.

When tests are worth writing

Jest is a tool; deciding what to test is the real skill. Good first candidates are pure functions with several branches, code that handles money or dates, bug fixes (write the failing test first, then fix), and anything you are scared to refactor. Poor candidates are trivial getters and code that mostly wires libraries together. Over this tutorial we will learn to test synchronous code, promises, timers, HTTP calls and user interfaces.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which three jobs does Jest bundle together?

    Jest finds and runs tests, gives you expect() with matchers, and offers mocks, spies and fake timers, all in one package.
  2. 2. What makes a Jest test fail?

    A test passes if its function finishes without throwing. A failed matcher throws an error with a clear message, and that is what Jest reports.
  3. 3. Which file name is picked up as a test file by default?

    Jest looks for files ending in .test or .spec (with a JavaScript or TypeScript extension) and for files inside tests folders.
  4. 4. Why can Jest run different test files in parallel safely?

    Isolation per file means one file cannot change modules or globals that another file sees, so workers can run files at the same time.

Summary

  • Jest is a test runner, an assertion library (expect) and a set of mocking tools in one package.
  • Install it with npm install --save-dev jest and run it with npm test.
  • Files named *.test.js or *.spec.js, or placed in __tests__, are test files by default.
  • test() registers a test; Jest runs the registered tests afterwards, and a thrown error means failure.
  • Each test file runs in isolation, which allows parallel workers.
  • Vitest has a nearly identical API; node:test is built into Node with no install.

Next: Your First Jest Test.