Quick Start (5 min): Catching Bugs Your Unit Tests Miss
High code coverage is a comfort blanket. Teams regularly celebrate 95% line coverage on pull requests, yet regressions still slip into production. Why? Because reaching a line of code is not the same as verifying what it does. If a developer flips an operator or strips an if condition, tests that lack assertions will still pass green.
Mutation testing evaluates your test suite by deliberately breaking your production code. It introduces tiny syntax mutations called mutants—such as swapping > for <=, stripping method calls, or inverting boolean conditions. If your test suite fails when a mutant is introduced, that mutant is killed. If the suite still passes, the mutant survived. A surviving mutant means your assertions missed the bug entirely.
Setting Up Stryker in a TypeScript Project
Install Stryker along with its TypeScript checker and Vitest runner plugin:
npm install --save-dev @stryker-mutator/core @stryker-mutator/vitest-runner @stryker-mutator/typescript-checker
Add a minimal configuration file named stryker.config.json in your project root:
{
"$schema": "https://raw.githubusercontent.com/stryker-mutator/stryker-js/master/packages/api/schema/stryker-core.json",
"packageManager": "npm",
"reporters": ["html", "clear-text", "progress"],
"testRunner": "vitest",
"coverageAnalysis": "perTest",
"checkers": ["typescript"],
"tsconfigFile": "tsconfig.json",
"mutate": [
"src/**/*.ts",
"!src/**/*.spec.ts",
"!src/**/*.test.ts"
]
}
Register the test runner shortcut in package.json:
{
"scripts": {
"test:mutate": "stryker run"
}
}
Run Stryker from your terminal:
npm run test:mutate
On a module with 150 unit tests, Stryker might generate 60 mutants in about 12 seconds. It executes relevant tests against each mutation and prints an immediate score breakdown to your terminal and to reports/mutation/mutation.html.
Deep Dive: Anatomy of a Surviving Mutant
Why do standard coverage tools deceive engineering teams? Consider this common tiered-discount calculation:
The Fragile Implementation
// src/discount.ts
export interface Customer {
id: string;
tier: 'REGULAR' | 'GOLD' | 'PLATINUM';
totalSpent: number;
}
export function calculateDiscountPercentage(customer: Customer): number {
if (customer.tier === 'PLATINUM' || customer.totalSpent >= 5000) {
return 20;
}
if (customer.tier === 'GOLD' && customer.totalSpent >= 1000) {
return 10;
}
return 0;
}
The “100% Coverage” Test That Verifies Nothing
Here is an all-too-common test written simply to satisfy an automated coverage check:
// src/discount.spec.ts
import { describe, it, expect } from 'vitest';
import { calculateDiscountPercentage } from './discount';
describe('calculateDiscountPercentage', () => {
it('executes without crashing for all branches', () => {
// Hits branch 1
calculateDiscountPercentage({ id: 'c1', tier: 'PLATINUM', totalSpent: 6000 });
// Hits branch 2
calculateDiscountPercentage({ id: 'c2', tier: 'GOLD', totalSpent: 2000 });
// Hits fallback
calculateDiscountPercentage({ id: 'c3', tier: 'REGULAR', totalSpent: 200 });
expect(true).toBe(true);
});
});
Run vitest run --coverage on this file and Istanbul reports 100% Statements, 100% Branches, and 100% Lines. Every line executed. Every path ran. Yet this test asserts zero business requirements. Even if you checked expect(typeof result).toBe('number'), a bug returning 99 instead of 20 would sail straight into production. Pair mutation testing with practices like property-based testing to discover unintended behavior across complex input spaces.
How Stryker Catches the Deception
Stryker generates 7 distinct mutants across these 14 lines:
- Mutant 1 (BinaryExpression): Mutates
customer.totalSpent >= 5000tocustomer.totalSpent > 5000. - Mutant 2 (EqualityOperator): Inverts
customer.tier === 'PLATINUM'tocustomer.tier !== 'PLATINUM'. - Mutant 3 (LogicalOperator): Changes
||to&&. - Mutant 4 (BlockStatement): Strips
return 20;into an empty block. - Mutant 5 (EqualityOperator): Flips
customer.tier === 'GOLD'tocustomer.tier !== 'GOLD'. - Mutant 6 (BinaryExpression): Mutates
customer.totalSpent >= 1000tocustomer.totalSpent > 1000. - Mutant 7 (LogicalOperator): Changes
&&to||.
Because the original test only checks expect(true).toBe(true), all 7 mutants survive. The mutation score drops to a blunt 0.00%. Traditional coverage gave this code an A+; Stryker awards it an F.
Killing the Mutants with Boundary Assertions
To eliminate surviving mutants, write tests that pin down exact outputs around boundary conditions:
// src/discount.spec.ts (Refactored)
import { describe, it, expect } from 'vitest';
import { calculateDiscountPercentage } from './discount';
describe('calculateDiscountPercentage', () => {
it('grants 20% to PLATINUM members regardless of spending', () => {
expect(calculateDiscountPercentage({ id: '1', tier: 'PLATINUM', totalSpent: 0 })).toBe(20);
});
it('grants 20% to non-platinum members reaching boundary of 5000', () => {
expect(calculateDiscountPercentage({ id: '2', tier: 'REGULAR', totalSpent: 5000 })).toBe(20);
expect(calculateDiscountPercentage({ id: '3', tier: 'REGULAR', totalSpent: 4999 })).toBe(0);
});
it('requires both GOLD tier and spending >= 1000 for 10% discount', () => {
expect(calculateDiscountPercentage({ id: '4', tier: 'GOLD', totalSpent: 1000 })).toBe(10);
expect(calculateDiscountPercentage({ id: '5', tier: 'GOLD', totalSpent: 999 })).toBe(0);
expect(calculateDiscountPercentage({ id: '6', tier: 'REGULAR', totalSpent: 1000 })).toBe(0);
});
});
Re-run Stryker: 7 mutants created, 7 mutants killed. Mutation score: 100%. The test suite now guards actual application behavior instead of merely walking the syntax tree.
Advanced Usage: Incremental Runs and CI Pipeline Optimization
Full mutation analysis on a large codebase is resource-heavy. If a project has 400 source files generating 3,500 mutants, a brute-force run can take 35 to 50 minutes. Here is how to keep CI runs under 2 minutes without sacrificing rigor.
1. Targeted Mutations on Changed Files Only
On pull requests, restrict mutation testing to modified files against your base branch:
# Extract modified TypeScript files compared to main
CHANGED_FILES=$(git diff --name-only origin/main...HEAD | grep '^src/.*\.ts$' | grep -v '\.spec\.ts$' | grep -v '\.test\.ts$' | paste -sd, -)
if [ -n "$CHANGED_FILES" ]; then
npx stryker run --mutate "$CHANGED_FILES"
else
echo "No source TypeScript files changed. Skipping mutation tests."
fi
2. Leveraging Incremental Mode and Concurrency
Stryker supports an incremental cache that skips testing code and tests that have not changed since the last run. Enable it in stryker.config.json:
{
"incremental": true,
"incrementalFile": ".stryker/incremental.json",
"concurrency": 4,
"timeoutMS": 5000,
"thresholds": {
"high": 80,
"low": 65,
"break": 60
}
}
incremental: Caches results in.stryker/incremental.json. On consecutive commits, Stryker skips untouched mutants. In practice, this drops an 8-minute run to under 30 seconds.concurrency: Controls parallel worker processes. Set this to match your CI runner vCPUs (e.g., 4 on a standard GitHub Actions runner).thresholds.break: Automatically fails the pipeline if the overall mutation score drops below 60%.timeoutMS: Kills hanging mutants quickly, preventing infinite loops created by condition mutations from freezing the runner.
3. Ignoring Safe Boilerplate
Not every line of code warrants mutation. You can exclude non-critical string formatting or logging with inline comments:
export function formatLogMessage(level: string, message: string): string {
// Stryker disable next-line StringLiteral: Logging formatting is non-critical
return `[${new Date().toISOString()}] [${level}] ${message}`;
}
Field Notes for Production Codebases
- Prioritize core business logic over plumbing: Focus mutation testing on calculation engines, authorization guards, and billing workflows. Skip UI components, data transfer objects, and thin database wrappers. Just as you might isolate front-end markup with Playwright component testing, mutation tests should concentrate on pure logic.
- Keep unit tests strictly in-memory: Stryker re-runs tests hundreds of times. If a single test takes 300ms because it hits Docker or an SQLite file, 80 mutants will stall your machine for 24 seconds. Consider using Vitest as a Jest replacement in TypeScript to optimize test execution speed and keep unit tests mock-isolated under 10ms per test.
- Distinguish “Survived” from “No Coverage”: In the HTML report, “No Coverage” means no test reached that line. “Survived” is far more concerning: your test executed the mutated line, observed incorrect output, and stayed completely silent.
- Target an 80% score, not 100%: Demanding 100% mutation coverage yields diminishing returns. Engineers end up asserting trivial formatting quirks or defensive checks that TypeScript already catches at build time. An 80–85% mutation score on critical modules guarantees high reliability without slowing down shipping velocity.

