| | |

Jest 15 ๐Ÿƒ Configuration โ€” jest.config.js and the defineConfig Helper

โฑ๏ธ Estimated read: 8 min | |

Jest’s configuration lives in a jest.config.js file at the project root, or in a jest key in package.json. The file exports a configuration object, and the defineConfig helper from the jest package provides type inference for that object. The config is optional for a project that follows the conventions, and it is necessary when the project deviates from themโ€”a custom test location, a transformer for TypeScript or JSX, a different test environment, or coverage settings that differ from the defaults.

This chapter covers the configuration file, the defineConfig helper that types it, and the options that most projects need to set. The sections that follow walk through the file discovery, the key options, and the projects configuration that runs the same tests under different environments.

Key point: jest.config.js exports a configuration object; the defineConfig helper from jest provides the TypeScript type for that object, and the file is optional when the project follows Jest’s conventions for test location and file naming.


a. The configuration file and the defineConfig helper

Jest discovers a configuration file in a fixed order. It checks the jest key in package.json, then jest.config.js, jest.config.ts, jest.config.mjs, jest.config.cjs, jest.config.json, and the .config variants. The first one found is the one Jest uses, and the file can be a JavaScript object, a function that returns the object, or a Promise that resolves to it.

// jest.config.js
/** @type {import('jest').Config} */
const config = {
  testEnvironment: "jsdom",
  testMatch: ["**/__tests__/**/*.js", "**/?(*.)+(spec|test).js"],
  collectCoverageFrom: ["src/**/*.js"],
};

module.exports = config;

The defineConfig helper is the typed form. It is a function that returns its argument, and the generic type is the Config type, so the object is type-checked.

// jest.config.js
const { defineConfig } = require("jest");

module.exports = defineConfig({
  testEnvironment: "jsdom",
  testMatch: ["**/__tests__/**/*.js"],
});

The helper adds no runtime behavior; it is the type annotation. The /** @type {import('jest').Config} */ comment above the plain object is the same annotation for a project that does not want the helper call.

The jest.config.ts file is the TypeScript form, and it requires the ts-node or tsx transformer to be installed. The defineConfig import from jest provides the type, and the export is the same object.

// jest.config.ts
import { defineConfig } from "jest";

export default defineConfig({
  testEnvironment: "jsdom",
});

The config can be a function that receives the globalConfig and returns the object. The function form is for a config that depends on the environment, such as a different testEnvironment in CI.

module.exports = (globalConfig) => ({
  testEnvironment: process.env.CI ? "node" : "jsdom",
});

b. The key options

The testEnvironment selects the DOM implementation. The default is node, and a component test suite uses jsdom or happy-dom. The testMatch and testPathIgnorePatterns control the file discovery, and the transform option configures the transformer for the file types Jest does not handle natively.

OptionPurpose
testEnvironmentnode, jsdom, happy-dom
testMatch / testPathIgnorePatternsFile discovery
transformFile transformer
setupFiles / setupFilesAfterEnvSetup scripts
moduleNameMapperModule alias
collectCoverageFromCoverage scope
coverageThresholdCoverage gate

The setupFiles runs before the test framework is installed, and the setupFilesAfterEnv runs after. The distinction matters: a setupFiles script can configure the environment before Jest’s globals exist, and a setupFilesAfterEnv script can use beforeEach, expect, and the matchers.

module.exports = {
  setupFiles: ["<rootDir>/test/setup-env.js"],
  setupFilesAfterEnv: ["<rootDir>/test/setup-matchers.js"],
};

The moduleNameMapper is the module alias. A @/ prefix that resolves to src/ in the build tool resolves to src/ in Jest through the mapper, and the test does not need the relative path.

module.exports = {
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
  },
};

The coverageThreshold is the coverage gate. A threshold of 80 fails the run when the coverage falls below 80 percent, which is the mechanism for preventing a coverage regression.

module.exports = {
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80,
    },
  },
};

c. The projects configuration

The projects option is an array of configurations that each run with their own settings. The array can contain the configuration objects directly or the paths to the config files.

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

The displayName is the label that appears in the test output, and the two projects run as separate groups. The pattern is for a project that has both pure-function tests and component tests, and the two need different environments.

The projects array is the replacement for the testEnvironment per directory. A project that uses a single config with a testEnvironment sets one environment for every test; the projects array gives each group its own.

The runner option is the custom test runner, and the testRunner is the legacy name. A project that uses jest-circus (the default) does not need to set it, and a project that uses jasmine2 sets the testRunner to jest-jasmine2. The option is for a project that has not migrated to the default runner.


Complete Example Session

// ============================================
// PART 1: THE CONFIG FILE
// ============================================
// jest.config.js
/** @type {import('jest').Config} */
const config = {
  testEnvironment: "jsdom",
  testMatch: ["**/__tests__/**/*.js", "**/*.test.js"],
  testPathIgnorePatterns: ["/node_modules/", "/dist/"],
  setupFilesAfterEnv: ["<rootDir>/test/setup.js"],
  moduleNameMapper: { "^@/(.*)$": "<rootDir>/src/$1" },
  collectCoverageFrom: ["src/**/*.js", "!src/**/*.test.js"],
  coverageThreshold: {
    global: { branches: 80, functions: 80, lines: 80, statements: 80 },
  },
};

module.exports = config;

// ============================================
// PART 2: THE defineConfig FORM
// ============================================
const { defineConfig } = require("jest");

module.exports = defineConfig({
  testEnvironment: "jsdom",
  testMatch: ["**/*.test.js"],
});

// ============================================
// PART 3: THE PROJECTS
// ============================================
module.exports = {
  projects: [
    {
      displayName: "unit",
      testMatch: ["<rootDir>/src/**/*.test.js"],
      testEnvironment: "node",
    },
    {
      displayName: "dom",
      testMatch: ["<rootDir>/src/**/*.dom.test.js"],
      testEnvironment: "jsdom",
    },
  ],
};

The parts covered the config file, the defineConfig form, and the projects.


Quick Reference

Discovery Order

PriorityFile
1package.json jest key
2jest.config.js
3jest.config.ts
4jest.config.mjs / .cjs / .json

Key Options

OptionDefaultPurpose
testEnvironmentnodeDOM implementation
testMatch**/*.test.*File discovery
transformBabelFile transformer
setupFilesAfterEnv[]Setup after framework
moduleNameMapper{}Module aliases
coverageThreshold{}Coverage gate

Projects

KeyPurpose
displayNameLabel in the output
testMatchPer-project discovery
testEnvironmentPer-project environment

Best Practices

โœ… Do This:

// Use defineConfig for type inference
module.exports = defineConfig({ testEnvironment: "jsdom" });   // โœ…

// Use setupFilesAfterEnv for matchers
setupFilesAfterEnv: ["<rootDir>/test/setup.js"];                // โœ…

// Use projects for different environments
projects: [{ displayName: "unit", testEnvironment: "node" }];   // โœ…

โŒ Don’t Do This:

// Put everything in package.json
// (harder to review)                                          // โŒ

// Use setupFiles for the matchers
setupFiles: [".../setup.js"]; // runs before expect exists      // โŒ

// Set the testEnvironment globally when two projects need different ones // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Config not discoveredWrong file namejest.config.js at root
Matchers not registeredUsed setupFilessetupFilesAfterEnv
Aliases not resolvingNo moduleNameMapperAdd the mapping
TypeScript config not loadingMissing transformerInstall ts-node

Real-World Examples

1. Basic config

module.exports = { testEnvironment: "jsdom" };

2. defineConfig

const { defineConfig } = require("jest");
module.exports = defineConfig({ testEnvironment: "jsdom" });

3. testMatch

testMatch: ["**/*.test.js"];

4. Ignore patterns

testPathIgnorePatterns: ["/node_modules/", "/dist/"];

5. Setup after env

setupFilesAfterEnv: ["<rootDir>/test/setup.js"];

6. Module mapper

moduleNameMapper: { "^@/(.*)$": "<rootDir>/src/$1" };

7. Coverage threshold

coverageThreshold: { global: { lines: 80 } };

8. Projects

projects: [{ displayName: "unit", testEnvironment: "node" }];

9. Function config

module.exports = (globalConfig) => ({ testEnvironment: "jsdom" });

10. Custom config path

jest --config ./config/jest.config.js

Visual

The Config File

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  jest.config.js                                         โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”           โ”‚
โ”‚  โ”‚ module.exports = {                       โ”‚           โ”‚
โ”‚  โ”‚   testEnvironment, testMatch, transform, โ”‚           โ”‚
โ”‚  โ”‚   setupFilesAfterEnv, moduleNameMapper,  โ”‚           โ”‚
โ”‚  โ”‚   coverageThreshold, projects            โ”‚           โ”‚
โ”‚  โ”‚ }                                        โ”‚           โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜           โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The defineConfig Helper

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  const { defineConfig } = require("jest");              โ”‚
โ”‚  module.exports = defineConfig({ testEnvironment: "jsdom" });โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  Type-checked configuration object                      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Setup Files

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  setupFiles            โ†’ before the framework           โ”‚
โ”‚  setupFilesAfterEnv    โ†’ after `expect` is available    โ”‚
โ”‚                                                         โ”‚
โ”‚  Use AfterEnv for custom matchers and beforeEach.       โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Projects

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  projects: [                                            โ”‚
โ”‚    { displayName: "unit", testEnvironment: "node" },    โ”‚
โ”‚    { displayName: "dom", testEnvironment: "jsdom" },    โ”‚
โ”‚  ]                                                      โ”‚
โ”‚                                                         โ”‚
โ”‚  Each project runs its own tests with its own settings. โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Config filejest.config.js
HelperdefineConfig from jest
Discovery orderpackage.json key, then jest.config.*
Test environmenttestEnvironment
Matchers setupsetupFilesAfterEnv
AliasesmoduleNameMapper
Multiple environmentsprojects array

Key takeaways:

  • The config file is optional for a conventional project. A project that follows Jest’s test file naming and location runs without a config. The file is for the project that deviates.
  • defineConfig is the typed form. It returns its argument with the Config type, which is the same annotation as the /** @type {import('jest').Config} */ comment.
  • setupFilesAfterEnv is for the matchers. The setupFiles runs before Jest’s globals exist, and the setupFilesAfterEnv runs after expect is available, which is where the custom matchers and beforeEach hooks belong.
  • moduleNameMapper is the alias. The @/ prefix that resolves to src/ in the build tool resolves to the same directory in Jest through the mapper.
  • The projects array is the per-environment split. A project with both pure-function tests and component tests gives each group its own testEnvironment and testMatch.

Remember: The config is the one place where the Jest-specific values live. The testEnvironment selects the DOM, the setupFilesAfterEnv registers the matchers, the moduleNameMapper resolves the aliases, and the projects array splits the suite by environment. Use defineConfig for the type, and the setupFilesAfterEnv for anything that needs expect.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!