Skip to content

jest

npm version License: MIT Node.js Jest ts-jest

> Base Jest configuration for jmlweb projects. TypeScript support, coverage settings, and sensible defaults out of the box.

  • 🔧 TypeScript Support: Configured for TypeScript projects with ts-jest
  • 📊 Coverage Configuration: Pre-configured with 80% coverage thresholds
  • 🎯 Sensible Defaults: Node.js environment, optimized test execution, clear mocks
  • Performance Optimized: Efficient test execution with proper module isolation
  • 🚀 Easy Extension: Factory function for easy customization
  • 📦 Zero Config: Works out of the box with minimal setup
Terminal window
pnpm add -D @jmlweb/jest-config jest ts-jest @types/jest

> 💡 Upgrading from a previous version? See the Migration Guide for breaking changes and upgrade instructions.

Create a jest.config.ts file in your project root:

import jestConfig from '@jmlweb/jest-config';
export default jestConfig;

Or use the factory function for customization:

import { createJestConfig } from '@jmlweb/jest-config';
export default createJestConfig({
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/src/test/setup.ts'],
});
jest.config.ts
import jestConfig from '@jmlweb/jest-config';
export default jestConfig;
jest.config.ts
import { createJestConfig } from '@jmlweb/jest-config';
export default createJestConfig({
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/src/test/setup.ts'],
testTimeout: 10000,
coverageThreshold: {
global: {
lines: 90,
functions: 90,
branches: 85,
statements: 90,
},
},
});
jest.config.ts
import { createJestConfig } from '@jmlweb/jest-config';
export default createJestConfig({
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/src/test/setup.ts'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},
});
jest.config.ts
import { createJestConfig } from '@jmlweb/jest-config';
export default createJestConfig({
coverageThreshold: {
global: {
lines: 60,
functions: 60,
branches: 60,
statements: 60,
},
},
});
jest.config.ts
import { createJestConfig } from '@jmlweb/jest-config';
export default createJestConfig({
testMatch: ['**/__tests__/**/*.ts', '**/*.test.ts'],
collectCoverageFrom: ['src/**/*.ts', '!src/**/*.d.ts'],
});

> Philosophy: Tests should run reliably with meaningful coverage metrics that enforce code quality without being overly strict.

This package provides a Jest configuration optimized for TypeScript projects with sensible coverage thresholds and test isolation. It balances strictness with practicality, enforcing coverage standards while keeping tests fast and maintainable.

80% Coverage Thresholds: Requires 80% coverage across all metrics

  • Why: 80% coverage strikes a good balance - it’s high enough to ensure most code paths are tested but not so high that you waste time testing trivial code or struggle to reach unrealistic goals. It catches most bugs while allowing flexibility for edge cases that are hard to test
  • Trade-off: Some projects may want higher coverage (90%+) or lower (60%). This is easily adjustable per project
  • When to override: Increase for critical systems (financial, healthcare), decrease for experimental projects or when initially adding tests to legacy code

Automatic Mock Clearing (clearMocks: true, restoreMocks: true): Resets mocks between tests

  • Why: Test isolation is crucial for reliable tests. Automatically clearing and restoring mocks prevents test interdependence and the dreaded “works in isolation but fails in suite” problem. This eliminates an entire class of flaky tests
  • Trade-off: Can’t rely on mock state persisting between tests. But tests shouldn’t share state anyway
  • When to override: Rarely needed - test isolation is a best practice

Node Environment by Default (testEnvironment: 'node'): Server-side testing environment

  • Why: Most TypeScript projects tested with Jest are Node.js backends or libraries. The Node environment is lighter and faster than jsdom. For React/browser code, developers can override to jsdom per project
  • Trade-off: Need to explicitly set jsdom for browser/React testing
  • When to override: For React components or browser-specific code - set testEnvironment: 'jsdom' in your project config

5 Second Test Timeout: Reasonable default for most tests

  • Why: Most unit tests should complete in milliseconds. 5 seconds is generous for integration tests while preventing truly hung tests from blocking CI indefinitely. It catches accidentally synchronous code or missing mocks
  • Trade-off: Some integration tests with real databases might need longer timeouts
  • When to override: For slow integration tests - increase per test suite or project-wide
SettingValueDescription
testEnvironmentnodeNode.js environment by default
moduleFileExtensions['ts', 'tsx', 'js', 'jsx', 'json']Supported file extensions
testMatch['**/*.{test,spec}.{ts,tsx,js,jsx}']Test file patterns
testTimeout5000Test timeout in milliseconds (5 seconds)
coverageThreshold.global.lines80Minimum line coverage
coverageThreshold.global.functions80Minimum function coverage
coverageThreshold.global.branches80Minimum branch coverage
coverageThreshold.global.statements80Minimum statement coverage
verbosetrueDetailed test output
clearMockstrueClear mocks between tests
restoreMockstrueRestore mocks after each test

The following patterns are excluded from coverage by default:

  • **/*.d.ts - TypeScript declaration files
  • **/*.config.{ts,js} - Configuration files
  • **/dist/** - Build output
  • **/build/** - Build directories
  • **/node_modules/** - Dependencies
  • **/coverage/** - Coverage reports
  • **/*.test.{ts,tsx,js,jsx} - Test files
  • **/*.spec.{ts,tsx,js,jsx} - Spec files

Tests are automatically discovered from:

  • **/*.test.{ts,tsx,js,jsx}
  • **/*.spec.{ts,tsx,js,jsx}
  • text - Text summary in terminal
  • json - JSON format for CI/CD integration
  • html - HTML coverage report (generated in coverage/ directory)

Use this configuration when you want:

  • ✅ Consistent testing setup across projects using Jest
  • ✅ TypeScript support out of the box
  • ✅ Coverage thresholds enforced
  • ✅ Sensible defaults for Node.js and browser projects
  • ✅ Easy customization and extension

For projects using Vitest, use @jmlweb/vitest-config instead.

You can extend or override the configuration for your specific needs:

import { createJestConfig } from '@jmlweb/jest-config';
export default createJestConfig({
// Add custom setup files
setupFilesAfterEnv: ['<rootDir>/src/test/setup.ts'],
// Custom test patterns
testMatch: ['**/*.test.ts', '**/__tests__/**/*.ts'],
// Custom environment
testEnvironment: 'jsdom',
// Path aliases
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
'^~/(.*)$': '<rootDir>/src/$1',
},
});

Add test scripts to your package.json:

{
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"test:ci": "jest --ci --coverage --maxWorkers=2"
}
}

Then run:

Terminal window
pnpm test # Run tests once
pnpm test:watch # Run tests in watch mode
pnpm test:coverage # Run tests with coverage
pnpm test:ci # Run tests in CI mode

The configuration uses ts-jest for TypeScript support. The default transform configuration includes:

  • esModuleInterop: true - Allows default imports from CommonJS modules
  • allowSyntheticDefaultImports: true - Allows default imports from modules with no default export

These settings ensure compatibility with modern TypeScript projects.

  • Node.js >= 20.11.0
  • Jest >= 29.0.0
  • ts-jest >= 29.0.0
  • @types/jest >= 29.0.0
  • TypeScript project (recommended, but not required)

This package requires the following peer dependencies:

  • jest (>=29.0.0)
  • ts-jest (>=29.0.0)
  • @types/jest (>=29.0.0)

> Note: If no breaking changes were introduced in a version, it’s safe to upgrade without additional steps.

No breaking changes have been introduced yet. This package follows semantic versioning. When breaking changes are introduced, detailed migration instructions will be provided here.

For version history, see the Changelog.

Need Help? If you encounter issues during migration, please open an issue.

See CHANGELOG.md for version history and release notes.

MIT