TypeScript Monorepo Testing with Turborepo and Nx
TypeScript monorepos multiply your testing surface area. Each package needs its own tests, but they share types, utilities, and fixtures. Turborepo and Nx handle the orchestration — running only what changed, caching results, and parallelizing across packages. This guide covers structuring shared test utilities, configuring Turborepo/Nx for test pipelines, handling cross-package TypeScript config, and optimizing CI for large repos.
Key Takeaways
Run only what changed. Turborepo's --filter=[HEAD^1] and Nx's affected commands run tests only for packages touched by recent commits — critical for repos with 20+ packages.
Shared test utilities live in a dedicated package. Create packages/test-utils with typed fixtures, mock factories, and helper functions. Every app and library imports from there.
Each package needs its own tsconfig.json and tsconfig.test.json. Monorepo root tsconfig is for IDE support only. Package-level configs control what each package compiles.
Cache test results, not just builds. Turborepo caches jest --ci output by default. Restored cache means zero test re-runs for unchanged code in CI.
Type-check across packages separately from linting and testing. tsc --build at the root verifies cross-package type compatibility. Run it as a separate pipeline step.
The Monorepo Testing Problem
In a single-package TypeScript project, testing is straightforward: one Jest config, one tsconfig, one test command. In a monorepo with 10–30 packages, the same naive approach breaks down:
npm testfrom the root runs all tests, every time, regardless of what changed- Shared test utilities get copy-pasted across packages
- TypeScript config drifts between packages — different strict settings, different module resolution
- CI takes 30 minutes when only 2 packages changed
Turborepo and Nx solve the orchestration problem. This guide focuses on the TypeScript-specific patterns that make monorepo testing maintainable.
Repo Structure
my-monorepo/
├── apps/
│ ├── api/ # Express API
│ └── web/ # Next.js frontend
├── packages/
│ ├── core/ # Shared business logic
│ ├── database/ # DB client and migrations
│ ├── ui/ # Shared React components
│ └── test-utils/ # Shared test utilities ← key package
├── turbo.json # Turborepo pipeline config
├── package.json # Root workspace config
└── tsconfig.base.json # Shared TypeScript base configShared TypeScript Configuration
Create a base tsconfig that all packages extend:
// tsconfig.base.json
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022"],
"module": "NodeNext",
"moduleResolution": "NodeNext",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"skipLibCheck": false,
"forceConsistentCasingInFileNames": true
}
}Each package extends it with package-specific settings:
// packages/core/tsconfig.json
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"],
"exclude": ["src/**/*.test.ts", "src/**/*.spec.ts"]
}// packages/core/tsconfig.test.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"types": ["jest", "node"],
"noEmit": true
},
"include": ["src"]
}The production tsconfig excludes test files. The test tsconfig includes them and adds test-specific type declarations.
The test-utils Package
Shared test utilities deserve a dedicated package, not a folder inside each app:
// packages/test-utils/package.json
{
"name": "@myrepo/test-utils",
"version": "1.0.0",
"private": true,
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts",
"./factories": "./src/factories/index.ts",
"./mocks": "./src/mocks/index.ts",
"./setup": "./src/setup/index.ts"
},
"devDependencies": {
"@types/jest": "*",
"jest": "*"
}
}Note: main and types point to TypeScript source, not compiled output. With moduleResolution: NodeNext and TypeScript path aliases, packages in the monorepo can import from each other's source directly — no build step needed for testing.
// packages/test-utils/src/factories/user.factory.ts
import type { User, Role } from '@myrepo/core';
let idCounter = 0;
export function buildUser(overrides: Partial<User> = {}): User {
idCounter++;
return {
id: `test-user-${idCounter}`,
email: `user${idCounter}@example.com`,
name: `Test User ${idCounter}`,
role: 'viewer' as Role,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
...overrides,
};
}
export function buildUsers(count: number, overrides: Partial<User> = {}): User[] {
return Array.from({ length: count }, () => buildUser(overrides));
}// packages/test-utils/src/mocks/database.mock.ts
import type { DatabaseClient } from '@myrepo/database';
export function createMockDatabase(): jest.MockedObject<DatabaseClient> {
return {
query: jest.fn(),
transaction: jest.fn((fn) => fn(createMockDatabase())),
close: jest.fn(),
users: {
findById: jest.fn(),
findMany: jest.fn(),
create: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
},
};
}// packages/test-utils/src/setup/jest-globals.ts
// Common Jest setup — import in jest.config.ts setupFilesAfterFramework
// Suppress console.error in tests unless DEBUG=true
if (!process.env.DEBUG) {
beforeEach(() => {
jest.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
jest.restoreAllMocks();
});
}Using shared utilities in a package:
// apps/api/src/users/users.service.test.ts
import { buildUser, buildUsers } from '@myrepo/test-utils/factories';
import { createMockDatabase } from '@myrepo/test-utils/mocks';
import { UsersService } from './users.service';
describe('UsersService', () => {
const db = createMockDatabase();
const service = new UsersService(db);
it('finds a user by id', async () => {
const user = buildUser({ id: 'known-id' });
db.users.findById.mockResolvedValue(user);
const result = await service.getUser('known-id');
expect(result).toEqual(user);
});
it('returns null for unknown user', async () => {
db.users.findById.mockResolvedValue(null);
const result = await service.getUser('unknown-id');
expect(result).toBeNull();
});
});Turborepo Pipeline Configuration
// turbo.json
{
"$schema": "https://turbo.build/schema.json",
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist/**"]
},
"test": {
"dependsOn": ["^build"],
"outputs": ["coverage/**"],
"cache": true,
"env": ["NODE_ENV", "DATABASE_URL"]
},
"test:unit": {
"dependsOn": [],
"outputs": [],
"cache": true
},
"test:integration": {
"dependsOn": ["^build"],
"outputs": [],
"cache": false,
"env": ["DATABASE_URL", "REDIS_URL"]
},
"typecheck": {
"dependsOn": ["^build"],
"outputs": [],
"cache": true
},
"lint": {
"dependsOn": [],
"cache": true
}
}
}Key decisions:
test:unithas no dependencies (no build needed) and is cachedtest:integrationis not cached (database state can differ)typecheckdepends on^build(needs dependencies compiled for cross-package type checking)
Running Affected Tests
The most important Turborepo flag for CI:
# Run tests only for packages changed since the last commit
npx turbo test --filter=[HEAD^1]
# Run tests for packages changed against main branch
npx turbo test --filter=[origin/main...HEAD]
# Run tests for a specific package and its dependents
npx turbo test --filter=@myrepo/core...For Nx:
# Run only affected tests
npx nx affected --target=test --base=origin/main --head=HEAD
# Show what would run without running
npx nx affected --target=test --base=origin/main --head=HEAD --dry-runPackage-Level Jest Configuration
Each package has its own jest config. Keep them consistent by using a shared factory:
// tools/jest-config/index.ts
import type { Config } from 'jest';
import path from 'path';
export function createJestConfig(packageDir: string): Config {
return {
preset: 'ts-jest',
testEnvironment: 'node',
rootDir: packageDir,
tsconfig: path.join(packageDir, 'tsconfig.test.json'),
moduleNameMapper: {
// Resolve workspace packages to source directly
'^@myrepo/(.*)$': '<rootDir>/../../packages/$1/src',
},
collectCoverageFrom: [
'src/**/*.ts',
'!src/**/*.test.ts',
'!src/**/*.d.ts',
'!src/index.ts',
],
coverageThresholds: {
global: {
branches: 80,
functions: 85,
lines: 85,
statements: 85,
},
},
};
}// packages/core/jest.config.ts
import { createJestConfig } from '../../tools/jest-config';
export default createJestConfig(__dirname);All packages share the same base config. Diverge only for legitimate reasons (different test environment, different module mapping).
Cross-Package Type Checking
TypeScript's project references enable incremental, dependency-aware type checking across packages. Set up a root tsconfig.json that references all packages:
// tsconfig.json (root)
{
"files": [],
"references": [
{ "path": "packages/core" },
{ "path": "packages/database" },
{ "path": "packages/ui" },
{ "path": "apps/api" },
{ "path": "apps/web" }
]
}Each package's tsconfig declares its own references:
// apps/api/tsconfig.json
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "dist",
"composite": true
},
"references": [
{ "path": "../../packages/core" },
{ "path": "../../packages/database" }
],
"include": ["src"],
"exclude": ["src/**/*.test.ts"]
}Run type checking across all packages:
npx tsc --build --dry # Show what would be compiled
npx tsc --build # Incremental build with type checkingThis is faster than tsc --noEmit on each package independently — TypeScript shares the intermediate results.
CI Optimization
# .github/workflows/ci.yml
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
# Determine what changed
changes:
runs-on: ubuntu-latest
outputs:
packages: ${{ steps.filter.outputs.changes }}
steps:
- uses: actions/checkout@v4
- uses: dorny/paths-filter@v3
id: filter
with:
filters: |
core: packages/core/**
database: packages/database/**
api: apps/api/**
web: apps/web/**
# Unit tests — fast, cached, parallelized
unit-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 2 # Need previous commit for --filter
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- name: Cache Turborepo
uses: actions/cache@v4
with:
path: .turbo
key: turbo-${{ github.sha }}
restore-keys: turbo-
- name: Run affected unit tests
run: npx turbo test:unit --filter=[HEAD^1] --cache-dir=.turbo
# Type checking — separate job, can run in parallel
typecheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npx tsc --build
# Integration tests — needs real services
integration-tests:
runs-on: ubuntu-latest
needs: unit-tests
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: test
POSTGRES_DB: testdb
options: >-
--health-cmd pg_isready
--health-interval 10s
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 2
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npx turbo test:integration --filter=[HEAD^1] --no-cache
env:
DATABASE_URL: postgresql://postgres:test@localhost/testdbRemote Caching
For teams with multiple developers, Turborepo's remote cache eliminates redundant CI runs:
# Set up Vercel remote cache (free for Turborepo)
npx turbo login
npx turbo link
# Or self-host with turbo-remote-cache packageWith remote caching, if Alice ran tests on a commit and they passed, Bob's CI for the same commit restores Alice's cache — zero test re-runs for unchanged code.
Common Mistakes
Single tsconfig for the entire monorepo. This works until packages need different settings. Give each package its own tsconfig.
Importing from package internals. import { util } from '@myrepo/core/src/internal/util' bypasses the package's public API and breaks encapsulation. Only import from the package's exports.
Running all tests on every PR. Without --filter or nx affected, a one-line change in packages/ui triggers tests for apps/api that don't depend on it.
Not caching test results. Turborepo caches by default, but you need consistent Jest output (use --ci flag) and consistent environment variables (declare them in turbo.json).
Shared global test state. Multiple packages run tests concurrently. Any shared resource (global variables, files, ports) causes flaky failures. Keep tests isolated.
TypeScript monorepo testing is a discipline problem as much as a tooling problem. The tooling (Turborepo, Nx, project references) gives you the infrastructure. The discipline — shared utilities, consistent configs, affect-aware runs — is what makes the repo maintainable at 20, 50, or 100 packages.