Jest 15 ๐ Configuration โ jest.config.js and the defineConfig Helper
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.
| Option | Purpose |
|---|---|
testEnvironment | node, jsdom, happy-dom |
testMatch / testPathIgnorePatterns | File discovery |
transform | File transformer |
setupFiles / setupFilesAfterEnv | Setup scripts |
moduleNameMapper | Module alias |
collectCoverageFrom | Coverage scope |
coverageThreshold | Coverage 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
| Priority | File |
|---|---|
| 1 | package.json jest key |
| 2 | jest.config.js |
| 3 | jest.config.ts |
| 4 | jest.config.mjs / .cjs / .json |
Key Options
| Option | Default | Purpose |
|---|---|---|
testEnvironment | node | DOM implementation |
testMatch | **/*.test.* | File discovery |
transform | Babel | File transformer |
setupFilesAfterEnv | [] | Setup after framework |
moduleNameMapper | {} | Module aliases |
coverageThreshold | {} | Coverage gate |
Projects
| Key | Purpose |
|---|---|
displayName | Label in the output |
testMatch | Per-project discovery |
testEnvironment | Per-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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Config not discovered | Wrong file name | jest.config.js at root |
| Matchers not registered | Used setupFiles | setupFilesAfterEnv |
| Aliases not resolving | No moduleNameMapper | Add the mapping |
| TypeScript config not loading | Missing transformer | Install 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
| Item | Value |
|---|---|
| Config file | jest.config.js |
| Helper | defineConfig from jest |
| Discovery order | package.json key, then jest.config.* |
| Test environment | testEnvironment |
| Matchers setup | setupFilesAfterEnv |
| Aliases | moduleNameMapper |
| Multiple environments | projects 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.
defineConfigis the typed form. It returns its argument with theConfigtype, which is the same annotation as the/** @type {import('jest').Config} */comment.setupFilesAfterEnvis for the matchers. ThesetupFilesruns before Jest’s globals exist, and thesetupFilesAfterEnvruns afterexpectis available, which is where the custom matchers andbeforeEachhooks belong.moduleNameMapperis the alias. The@/prefix that resolves tosrc/in the build tool resolves to the same directory in Jest through the mapper.- The
projectsarray is the per-environment split. A project with both pure-function tests and component tests gives each group its owntestEnvironmentandtestMatch.
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.
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!