Jest Configuration for Monorepos: Projects, Path Aliases, and Coverage

Jest Configuration for Monorepos: Projects, Path Aliases, and Coverage

Jest is the most widely used JavaScript testing framework, and configuring it well in a monorepo pays dividends in test reliability and developer experience. There are two main approaches to monorepo Jest configuration: a single root config that uses the projects array to aggregate all packages, or per-package configs that each run independently. This guide covers both approaches, along with TypeScript path alias resolution, shared setup files, custom matchers, and the tricky problem of merging coverage reports from multiple packages.

Two Configuration Models

Before writing any config, decide which model fits your monorepo.

Centralized (root projects array): One jest.config.js at the root references every package. You run jest once and it tests everything. Good for small-to-medium monorepos where you always want to run all tests together, and where configuration is uniform.

Distributed (per-package configs): Each package has its own jest.config.ts. You run Jest per-package via nx test my-package, turbo run test, or yarn workspace @myorg/utils jest. Good for large monorepos with heterogeneous configs (some packages use jsdom, some use node, some use React transforms, some don't).

Most real monorepos end up with a hybrid: per-package configs that all extend a shared root preset. That's what this guide focuses on.

The Root Preset

The root preset is not itself a runnable Jest configuration — it's a shared base that each package config extends:

// jest.preset.js (workspace root)
module.exports = {
  testMatch: [
    '**/__tests__/**/*.[jt]s?(x)',
    '**/?(*.)+(spec|test).[jt]s?(x)',
  ],
  testPathIgnorePatterns: [
    '/node_modules/',
    '/dist/',
    '/.next/',
    '/build/',
  ],
  transform: {
    '^.+\\.[tj]sx?$': ['@swc/jest', {
      jsc: {
        parser: {
          syntax: 'typescript',
          tsx: true,
          decorators: true,
        },
        transform: {
          react: {
            runtime: 'automatic',
          },
        },
      },
    }],
  },
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
  collectCoverageFrom: [
    'src/**/*.{ts,tsx}',
    '!src/**/*.d.ts',
    '!src/**/*.stories.{ts,tsx}',
    '!src/index.ts',
    '!src/**/__mocks__/**',
  ],
};

Using @swc/jest instead of ts-jest or babel-jest dramatically speeds up transforms — SWC is written in Rust and typically 20-50x faster than Babel for TypeScript. Install it with:

npm install --save-dev @swc/jest @swc/core

Per-Package jest.config.ts

Each package extends the root preset and adds package-specific settings:

// packages/ui/jest.config.ts
import type { Config } from 'jest';

const config: Config = {
  displayName: 'ui',
  preset: '../../jest.preset.js',
  testEnvironment: 'jsdom',
  setupFilesAfterFramework: [
    '<rootDir>/../../jest.setup.ts',
    '<rootDir>/src/test-setup.ts',
  ],
  moduleNameMapper: {
    '\\.css$': '<rootDir>/../../__mocks__/styleMock.js',
    '\\.svg$': '<rootDir>/../../__mocks__/svgMock.js',
    '^@myorg/(.*)$': '<rootDir>/../../packages/$1/src/index.ts',
  },
  coverageDirectory: '../../coverage/packages/ui',
};

export default config;
// packages/api-client/jest.config.ts
import type { Config } from 'jest';

const config: Config = {
  displayName: 'api-client',
  preset: '../../jest.preset.js',
  testEnvironment: 'node',  // API clients don't need jsdom
  setupFilesAfterFramework: ['<rootDir>/../../jest.setup.ts'],
  moduleNameMapper: {
    '^@myorg/(.*)$': '<rootDir>/../../packages/$1/src/index.ts',
  },
  coverageDirectory: '../../coverage/packages/api-client',
};

export default config;

The testEnvironment difference is important: jsdom for UI packages (emulates the browser DOM), node for server-side or pure utility packages. Using jsdom everywhere wastes time spinning up DOM emulation for packages that don't need it.

The projects Array for Root Aggregation

If you want a single jest command at the root to run everything:

// jest.config.js (workspace root — aggregator only, not extended by packages)
module.exports = {
  projects: [
    '<rootDir>/packages/utils',
    '<rootDir>/packages/ui',
    '<rootDir>/packages/api-client',
    '<rootDir>/packages/auth',
    '<rootDir>/apps/web',
    '<rootDir>/apps/dashboard',
  ],
  // Root-level coverage merges all packages
  collectCoverage: false, // Per-package coverage is collected when running individual packages
  coverageReporters: ['text', 'lcov', 'html'],
};

Each path in projects points to a directory containing a jest.config.ts. Jest discovers and runs them all, using each package's own config. This gives you the benefits of per-package configuration while still being able to run jest --coverage at the root to get a merged report.

moduleNameMapper for TypeScript Path Aliases

TypeScript path aliases (configured in tsconfig.base.json) don't work in Jest without additional configuration because Jest uses its own module resolver that doesn't read TypeScript config files. You need to replicate your path aliases in moduleNameMapper.

Given this tsconfig.base.json:

{
  "compilerOptions": {
    "paths": {
      "@myorg/utils": ["packages/utils/src/index.ts"],
      "@myorg/ui": ["packages/ui/src/index.ts"],
      "@myorg/ui/*": ["packages/ui/src/*"],
      "@myorg/api-client": ["packages/api-client/src/index.ts"],
      "@myorg/auth": ["packages/auth/src/index.ts"],
      "@myorg/test-utils": ["packages/test-utils/src/index.ts"]
    }
  }
}

The equivalent moduleNameMapper:

// jest.preset.js
module.exports = {
  // ... other config
  moduleNameMapper: {
    '^@myorg/utils$': '<rootDir>/../../packages/utils/src/index.ts',
    '^@myorg/ui$': '<rootDir>/../../packages/ui/src/index.ts',
    '^@myorg/ui/(.*)$': '<rootDir>/../../packages/ui/src/$1',
    '^@myorg/api-client$': '<rootDir>/../../packages/api-client/src/index.ts',
    '^@myorg/auth$': '<rootDir>/../../packages/auth/src/index.ts',
    '^@myorg/test-utils$': '<rootDir>/../../packages/test-utils/src/index.ts',
    // Non-JS assets
    '\\.css$': '<rootDir>/../../__mocks__/style-mock.js',
    '\\.module\\.css$': 'identity-obj-proxy',
    '\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$': '<rootDir>/../../__mocks__/file-mock.js',
  },
};

A cleaner alternative is jest-module-name-mapper which reads your tsconfig automatically:

npm install --save-dev jest-module-name-mapper
// jest.preset.js
const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./tsconfig.base.json');

module.exports = {
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {
    prefix: '<rootDir>/../../',
  }),
};

This approach stays in sync with tsconfig.base.json automatically as you add new packages.

Shared Setup Files and Custom Matchers

setupFilesAfterFramework runs after the test framework is installed in the environment. This is where you add custom matchers, configure Testing Library, and set up global mocks.

// jest.setup.ts (workspace root)
import '@testing-library/jest-dom';
import { server } from './mocks/server'; // MSW mock server

// Start MSW before all tests
beforeAll(() => server.listen({ onUnhandledRequest: 'warn' }));

// Reset handlers after each test
afterEach(() => server.resetHandlers());

// Clean up after all tests
afterAll(() => server.close());

// Suppress specific console noise in tests
const originalConsoleError = console.error;
beforeAll(() => {
  console.error = (...args: unknown[]) => {
    if (
      typeof args[0] === 'string' &&
      args[0].includes('Warning: ReactDOM.render is deprecated')
    ) {
      return;
    }
    originalConsoleError(...args);
  };
});
afterAll(() => {
  console.error = originalConsoleError;
});

For custom matchers, create a dedicated file:

// jest.custom-matchers.ts
import { expect } from '@jest/globals';

declare global {
  namespace jest {
    interface Matchers<R> {
      toBeWithinRange(min: number, max: number): R;
      toMatchDateString(expected: string): R;
      toHaveBeenCalledWithObject(expected: object): R;
    }
  }
}

expect.extend({
  toBeWithinRange(received: number, min: number, max: number) {
    const pass = received >= min && received <= max;
    return {
      pass,
      message: () => pass
        ? `expected ${received} not to be within [${min}, ${max}]`
        : `expected ${received} to be within [${min}, ${max}]`,
    };
  },

  toMatchDateString(received: Date, expected: string) {
    const receivedStr = received.toISOString().split('T')[0];
    const pass = receivedStr === expected;
    return {
      pass,
      message: () => `expected ${receivedStr} to match date string ${expected}`,
    };
  },

  toHaveBeenCalledWithObject(received: jest.Mock, expected: object) {
    const calls = received.mock.calls;
    const pass = calls.some(call =>
      call.some(arg =>
        typeof arg === 'object' &&
        Object.entries(expected).every(([k, v]) => arg[k] === v)
      )
    );
    return {
      pass,
      message: () => pass
        ? `expected mock not to have been called with object matching ${JSON.stringify(expected)}`
        : `expected mock to have been called with object matching ${JSON.stringify(expected)}`,
    };
  },
});

Include it in your root setup:

// jest.setup.ts
import './jest.custom-matchers';

Merged Coverage Reports Across Packages

Getting a unified coverage view across all packages requires a bit of extra work because each package writes its own LCOV file to a separate directory.

First, configure each package to output LCOV:

// packages/*/jest.config.ts
const config = {
  coverageReporters: ['text', 'lcov', 'json'],
  coverageDirectory: '../../coverage/packages/<package-name>',
};

Then merge them with lcov-result-merger or a custom script:

npm install --save-dev lcov-result-merger
// package.json (workspace root)
{
  "scripts": {
    "test:coverage": "turbo run test -- --coverage",
    "coverage:merge": "lcov-result-merger 'coverage/**/lcov.info' coverage/merged/lcov.info",
    "coverage:report": "genhtml coverage/merged/lcov.info --output-directory coverage/report",
    "coverage": "npm run test:coverage && npm run coverage:merge && npm run coverage:report"
  }
}

Alternatively, configure Jest at the root level to collect coverage across all projects:

// jest.config.js (root aggregator)
module.exports = {
  projects: [ /* ... */ ],
  // When running jest --coverage at root, collect from all packages
  coverageDirectory: '<rootDir>/coverage/merged',
  collectCoverageFrom: [
    'packages/*/src/**/*.{ts,tsx}',
    'apps/*/src/**/*.{ts,tsx}',
    '!**/node_modules/**',
    '!**/*.d.ts',
    '!**/*.stories.{ts,tsx}',
  ],
  coverageReporters: ['text-summary', 'lcov', 'html'],
  coverageThreshold: {
    global: {
      statements: 80,
      branches: 75,
      functions: 85,
      lines: 80,
    },
  },
};

For uploading to Codecov, the codecov-action can handle multiple LCOV files:

# .github/workflows/ci.yml
- name: Upload coverage
  uses: codecov/codecov-action@v4
  with:
    files: ./coverage/**/lcov.info
    flags: unit
    fail_ci_if_error: true

Handling Slow Test Suites

As your monorepo grows, even individual packages can accumulate slow test suites. Jest's --shard flag lets you split a package's tests across multiple CI runners:

# GitHub Actions matrix strategy
strategy:
  matrix:
    shard: [1/4, 2/4, 3/4, 4/4]

steps:
  - run: npx jest --shard=${{ matrix.shard }} --coverage

Collect the shard coverage files and merge:

  merge-coverage:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v4
        with:
          pattern: coverage-shard-*
          merge-multiple: true
          path: coverage/shards

      - run: npx lcov-result-merger 'coverage/shards/**/lcov.info' coverage/merged/lcov.info

Conclusion

Jest monorepo configuration works best when you establish a root preset that handles shared concerns — transforms, file extensions, coverage collection patterns, asset mocks — and let each package extend it with only the overrides it needs. TypeScript path aliases require explicit mapping in moduleNameMapper, either manually maintained or auto-generated from tsconfig.base.json via pathsToModuleNameMapper. Shared setup files and custom matchers keep tests DRY and improve readability. Coverage merging with lcov-result-merger or Jest's root aggregator config gives you a single view of test coverage across the entire monorepo, which is essential for tracking quality trends over time.

Read more

Start now free