Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 30 ยท Jest in Real Projects

Configuring Jest

Configure Jest with jest.config.js: testEnvironment, testMatch, setup files, moduleNameMapper, transform and projects, plus a runnable stand-in config loader.

Jest works with no configuration at all, and that is a fine way to start. Sooner or later a real project needs more: a browser-like environment for UI code, a file that runs before every test, a path alias such as @/utils, or a TypeScript transform. All of that lives in one place, the Jest configuration.

This lesson walks through the options you will actually touch, and shows how Jest decides what to run. If you are still new to the command line, read The Jest CLI and Watch Mode first.

Real versus stand-in. Config files and commands are real Jest usage, shown read-only because the site cannot run the jest package. The TryIt blocks run a small stand-in that mimics three ideas: merging your config over defaults, matching test files with globs, and rewriting import paths. It is not Jest's code, so treat its output as an illustration of the concepts.

Where config lives

jest.config.js A normal module that exports an object.
package.json A "jest" key for small setups.
CLI flags --config or one-off overrides.

Keep one source of truth. Jest complains if it finds several.

1 / 2

A first jest.config.js

Create jest.config.js in the project root. It is plain JavaScript, so you can use comments, variables and conditions:

JavaScript
/** @type {import('jest').Config} */
module.exports = {
  testEnvironment: "node",
  clearMocks: true,
  testMatch: ["**/*.test.js"],
};

The @type comment gives your editor autocomplete for every option. With "type": "module" in package.json, write export default { ... } instead. Jest also reads jest.config.ts if ts-node is installed, and a "jest" key in package.json. You can generate a starter file with npx jest --init, which asks a few questions.

Run Jest with a different file using npx jest --config ./configs/jest.ci.js. To see the final merged result, including defaults, run npx jest --showConfig. That command is the fastest way to answer "why is my test not picked up?"

testEnvironment

Each test file runs inside an environment that provides its globals.

  • "node" is the default in recent Jest versions. You get Node's globals and no window or document.
  • "jsdom" simulates a browser page in plain JavaScript, so document.querySelector and window work. It needs the separate jest-environment-jsdom package. Testing UI with jsdom and Testing Library builds on it.

You can pick an environment for one file with a docblock at the very top:

JavaScript
/**
 * @jest-environment jsdom
 */
test("has a document", () => {
  expect(document.body).not.toBeNull();
});

This is useful when most of your tests are server code and only a few touch the DOM.

testMatch and friends

By default Jest runs files inside a __tests__ folder and files ending in .test.js or .spec.js (and the .ts, .jsx, .tsx versions). Change that with testMatch, a list of glob patterns, or with testRegex. Do not set both.

Other options in the same family:

Option Purpose
roots Folders Jest searches for tests and modules.
testPathIgnorePatterns Regexes for paths to skip, such as /dist/.
moduleFileExtensions Extensions Jest tries when you import without one.
testTimeout Default timeout in milliseconds for each test (5000 unless changed).
verbose Print every test name, not only a summary.

Setup files

Two options run code before your tests, and the difference matters:

  • setupFiles run before the test framework is installed. There is no expect or beforeEach yet. Use them to set environment variables or polyfill a global.
  • setupFilesAfterEnv run after the framework is ready, once per test file. Use them for beforeEach hooks, expect.extend calls and global mock clean-up.
JavaScript
// jest.setup.js
expect.extend({
  toBeEven(received) {
    const pass = received % 2 === 0;
    return { pass, message: () => `expected ${received} ${pass ? "not " : ""}to be even` };
  },
});

afterEach(() => {
  jest.restoreAllMocks();
});
JavaScript
// jest.config.js
module.exports = {
  setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
};

<rootDir> is a token Jest replaces with the directory that holds the config. Always use it for paths, so the config works no matter where you launch the command. For how custom matchers work, see Errors and Custom Matchers.

moduleNameMapper

Many projects use path aliases such as import { fmt } from "@/lib/format". Your bundler understands that alias, but Jest does not, so you tell it. Keys are regular expressions, and values are replacement paths, where $1 refers to the first capture group:

JavaScript
module.exports = {
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
    "\\.(css|less)$": "<rootDir>/test/styleMock.js",
    "\\.(png|jpg|svg)$": "<rootDir>/test/fileMock.js",
  },
};

The second and third rules are the other common use. Jest cannot execute a stylesheet or image, so you map them to a tiny module that exports an empty object or a string.

transform

Jest runs Node's module system, which cannot read TypeScript, JSX or the newest syntax directly. A transform converts each file before it is executed. The default transform is babel-jest, which applies your Babel config. To use something else:

JavaScript
module.exports = {
  transform: {
    "^.+\\.tsx?$": "ts-jest",
  },
};

Setting transform replaces the default, so list every file type you need. Results are cached on disk, so unchanged files are not transformed again. TypeScript, Babel and CI compares the options in detail.

Projects

A project is a group of tests with its own configuration. Use the projects option when one repository holds different kinds of code, such as a Node API and a browser UI, or when you keep unit and integration tests apart:

JavaScript
module.exports = {
  projects: [
    { displayName: "server", testEnvironment: "node", testMatch: ["<rootDir>/server/**/*.test.js"] },
    { displayName: "ui", testEnvironment: "jsdom", testMatch: ["<rootDir>/ui/**/*.test.js"] },
  ],
};

One jest run then executes both groups, each in its own environment, and the report labels the files with displayName. Each project can also point to its own config file or folder.

Stand-in 1: merge, match and map

The stand-in below is a tiny config loader. It applies defaults to your config, turns a glob into a regular expression to decide which files are tests, and rewrites an aliased import the way moduleNameMapper does. Real Jest uses the micromatch library for globs, so its rules cover more cases than this toy.

Node.js A toy Jest config loader

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The loader prints a warning for the misspelled option, because real Jest also warns about unknown options and a typo in config is one of the most common ways to lose an afternoon. Notice that **/ matches zero or more folders, so src/sum.test.js and a deeply nested file both count as tests.

Stand-in 2: projects

With projects, each file is claimed by the first project whose patterns match it, and that project's settings apply. This second sketch shows the grouping only. It is a model of the idea, not of Jest's scheduler.

Node.js Grouping files into projects

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Common mistakes

  • Setting transform and losing Babel. Overriding transform removes the default babel-jest entry. Add it back explicitly if you still need it.
  • Hard-coded absolute paths. Use <rootDir> so the config works on every machine and in CI.
  • Both testMatch and testRegex. Jest refuses that combination. Pick one.
  • Putting beforeEach in setupFiles. It runs before the framework exists. Use setupFilesAfterEnv.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command prints the final configuration Jest will use, including defaults?

    --showConfig prints the merged configuration as JSON. --init creates a starter file, --listTests lists matched files and --verbose changes the report.
  2. 2. You want to call expect.extend once for every test file. Where should that code go?

    setupFilesAfterEnv runs after the test framework is installed, so expect and the hooks exist. setupFiles runs too early for that.
  3. 3. What does the moduleNameMapper rule "^@/(.*)$": "<rootDir>/src/$1" do?

    The key is a regular expression and $1 refers to the captured text, so the alias is replaced by a real path.
  4. 4. When is the projects option most useful?

    Each project has its own configuration, so server and UI code can run in different environments in one jest run.

Summary

  • Jest reads jest.config.js (or a "jest" key in package.json); npx jest --showConfig shows the merged result.
  • testEnvironment chooses node or jsdom, and a docblock can change it per file.
  • testMatch decides which files are tests; setupFilesAfterEnv is the place for hooks and custom matchers.
  • moduleNameMapper rewrites aliases and stubs out CSS and images; transform converts TypeScript and JSX.
  • projects lets one repository run several configurations together.

Next, find out how much of your code the tests actually exercise in Coverage and Test Quality.