skip to content

In a Jest 30 monorepo with a jsdom React package and a node API package, how do you run both through one projects config, and what must stay at the root?

level: seniorimportance: should knowfreq 32%

answer

  1. one run, several configurations
  2. displayName as the handle
  3. run-wide options live at the root
  4. rootDir resolves per project

basics

~20 s

projects lists paths, globs or inline config objects, and each entry becomes its own project with its own rootDir, testEnvironment, transform and moduleNameMapper. Run-wide options such as reporters, maxWorkers and coverageThreshold belong only in the root config.

solid answer

~40 s

`projects` takes an array of directory paths, globs such as `'<rootDir>/packages/*'`, or inline config objects. Each entry is a separate project with its own configuration, so the React package can set `testEnvironment: 'jsdom'` and an alias in `moduleNameMapper` while the API package stays on `node`, and one `jest` invocation runs both. Give every project a `displayName`: Jest prints it next to each result, and `--selectProjects web` runs one project by that name. Some options are run-wide and only work in the root config, among them `bail`, `reporters`, `maxWorkers`, `coverageThreshold` and `testSequencer`; inside a project Jest warns that the option is not supported and asks you to move it. `<rootDir>` resolves to each project's own root. To filter files across projects, Jest 30 uses `--testPathPatterns`, renamed from `--testPathPattern`.

code

javascript · 31 lines
javascript
// jest.config.js at the repository root
const {defineConfig} = require('jest');

const base = {
  transform: {'\\.[jt]sx?$': ['babel-jest', {rootMode: 'upward'}]},
  transformIgnorePatterns: ['/node_modules/(?!(package-a)/)'],
};

module.exports = defineConfig({
  // run-wide options stay here
  maxWorkers: '50%',
  projects: [
    {
      ...base,
      displayName: 'web',
      rootDir: '<rootDir>/packages/web',
      testEnvironment: 'jsdom',
      moduleNameMapper: {
        '^@/(.*)$': '<rootDir>/src/$1',
        '\\.css$': '<rootDir>/test/style-stub.js',
      },
      setupFilesAfterEnv: ['<rootDir>/test/after-env.js'],
    },
    {
      ...base,
      displayName: 'api',
      rootDir: '<rootDir>/packages/api',
      testEnvironment: 'node',
    },
  ],
});

go deeper

for a junior

Recall that projects runs several configurations in one jest command and that displayName labels each one.

for a middle

Explain which options belong in each project and which only work at the root, and how --selectProjects and --testPathPatterns narrow a run.

for a senior

Catch the quiet failures: run-wide options ignored inside a project, a repository-wide jsdom setting slowing server tests, and projects that cannot be selected.

for a principal

Choose how a monorepo shares Jest configuration, a root projects file with a shared base versus per-package configs, and who owns changes to it.

## What `projects` is `projects` lets **one Jest run execute several configurations side by side**. Without it, every test file shares one configuration. With it, each entry is a **project** with its own test environment, transforms, module mapping and setup files, and Jest schedules all of their test files across one pool of workers and prints one combined summary. An entry can be: - a **directory path**, where Jest reads that directory's own config file or `jest` key; - a **glob**, such as `'<rootDir>/packages/*'`, expanding to one project per matching directory; - an **inline config object**, convenient when the packages have no config of their own. Jest stops with a `Two projects resolved to the same config path` error if two entries point at the same configuration. ## Inline objects or one config per package? - **Inline objects** keep the whole picture in one root file, which suits a small number of packages and makes shared settings easy to spread. - **A path or glob per package** lets each package own a `jest.config.js` next to its code, so a package team changes its own setup and can also run Jest from inside the package. The root file then holds only `projects` and the run-wide options. - **Either way, each project is resolved on its own**: its `rootDir` is its own directory, and path tokens such as `<rootDir>` in its options refer to that directory. ## Per-project options versus root-only options | Belongs in each project | Belongs only in the root config | |---|---| | `displayName`, `rootDir`, `testEnvironment` | `bail`, `maxWorkers`, `reporters` | | `transform`, `transformIgnorePatterns` | `coverageThreshold`, `coverageReporters` | | `moduleNameMapper`, `setupFiles`, `setupFilesAfterEnv` | `testSequencer`, `randomize`, `testFailureExitCode` | | `testMatch`, `testPathIgnorePatterns`, `globalSetup` | `watchPlugins`, `workerIdleMemoryLimit` and other worker settings | Root-only options describe the **run**, not a set of files. Set one inside a project and Jest warns instead of applying it: ```plaintext Option "coverageThreshold" is not supported in an individual project configuration. Move it to the root configuration. ``` Run-wide CLI flags such as `--ci`, `--updateSnapshot` and `--watch` belong to the run as well. ## Building the monorepo config 1. **One entry per package**, each with a `displayName` (`web`, `api`) and its own `rootDir`. 2. **Environment per package**: `jsdom` for the React package, which needs `jest-environment-jsdom` installed, and the `node` default for the API package. 3. **Resolution per package**: the alias mapping and style stubs live in the web project; `<rootDir>` inside a project points at that project's root, so `'<rootDir>/src/$1'` lands in the right package. 4. **Share common settings deliberately.** Define a base object, such as the transform map and `transformIgnorePatterns`, and spread it into every project. Writing the per-project options inside each entry makes it visible which package gets what, rather than relying on how root-level values reach each project. 5. **Keep run-wide options at the root**, alongside `projects`. ## Running a slice of the monorepo - `jest --selectProjects web` runs only the projects whose `displayName` matches. Jest identifies projects by that name, so every project should declare one. - `jest --testPathPatterns "packages/api/.*"` filters test files by path across all projects. Jest 30 renamed the flag from `--testPathPattern` and accepts several patterns. - A `globalSetup` configured in a project is triggered only when at least one test from that project runs, so selecting `web` does not start the API package's global setup. ## Typical failures - **Everything in jsdom.** Setting `testEnvironment: 'jsdom'` once for the whole repository slows the API tests and can resolve browser builds of server dependencies. One environment per project avoids both. - **Threshold not enforced.** A `coverageThreshold` placed in a project produces only a validation warning, and the run still passes. - **`--selectProjects` matching nothing.** A project without `displayName` cannot be selected by name. - **Two configurations at one level.** A package with both `jest.config.js` and a `jest` key in `package.json` stops with `Multiple configurations found`; keep one, or pass `--config` explicitly.

  • What happens if a Jest 30 package has both a jest.config.js and a jest key in its package.json?
    Implicit config resolution refuses to choose. Jest stops with `Multiple configurations found`, lists both locations, and asks you to remove the unused one or select one explicitly with `--config`.
  • Why does a coverageThreshold placed in one Jest project not fail the run?
    `coverageThreshold` is a run-wide option that only takes effect in the root config. Inside a project, Jest prints a validation warning saying the option is not supported in an individual project configuration and does not enforce it, so the run passes.

  • Each project needs its own separate jest invocation to run.
  • --selectProjects matches each project's folder name, so displayName is optional.
  • A coverageThreshold set inside a project applies to that project's files.
  • <rootDir> inside a project always points at the repository root.
  • --testPathPattern is still the Jest 30 flag for filtering files by path.

Assumes Jest 30.5.2: --testPathPatterns replaced Jest 29's --testPathPattern, and the documented list of root-only options is the Jest 30 one.