Tests guard your code. So who guards your tests? A test that runs every line can still stay green when >= is swapped for >, because no test checks the case where the two differ.
The answer is mutation testing: it tests your tests. The tool makes small mistakes in your code on purpose, one at a time, then runs the tests. If a test now fails, good: the mistake was caught. If the tests stay green, your tests don't check that part. Picture an airport x-ray screener who is being tested by a supervisor. The supervisor puts a bag holding a fake forbidden item into the x-ray machine on purpose. If the screener finds the item, the check works. If the bag is not stopped, the way they check needs fixing. In this picture, the screener is your test, the supervisor is the mutation testing tool, and the fake forbidden item is that small mistake.
How it works
- The mutation testing tool changes one small piece of your code, for example
>=into>. This changed version of the code is called a mutant. - All the tests run against that mutant.
- A test fails: the mutant is killed. Your tests caught the change.
- Every test still passes: the mutant survived. The code's behaviour changed, but no test failed. That means your tests are weak in that spot.
- A mutant on a line no test ever runs gets the status NoCoverage. No test can kill it.
Mutation score = caught mutants divided by all mutants, times 100%. 6 killed out of 10 mutants means a score of 60%. A mutant with the status Timeout (the tests were stopped because they took too long, for example in an endless loop) also counts as caught, like killed.
The mutants of calculateShipping
The function is the same as in Test Coverage & Strategy. Shipping costs $20, members pay half, and orders from $100 ship free.
// src/shipping.js
export function calculateShipping(total, member) {
let fee = 20;
if (member) {
fee = fee / 2;
}
if (total >= 100) {
fee = 0;
}
return fee;
}
Stryker, the mutation testing tool for JavaScript and TypeScript, makes 10 mutants of this code. The line numbers in the table count from export function (line 1), because // src/shipping.js only names the file. The Mutator column holds the kind of change Stryker applies:
| # | Mutator | Line | Original | Mutant |
|---|---|---|---|---|
| 1 | BlockStatement | 1 | the function body | {} (returns undefined) |
| 2 | ConditionalExpression | 3 | if (member) |
if (true) |
| 3 | ConditionalExpression | 3 | if (member) |
if (false) |
| 4 | BlockStatement | 3 | { fee = fee / 2; } |
{} |
| 5 | ArithmeticOperator | 4 | fee / 2 |
fee * 2 |
| 6 | ConditionalExpression | 6 | if (total >= 100) |
if (true) |
| 7 | ConditionalExpression | 6 | if (total >= 100) |
if (false) |
| 8 | EqualityOperator | 6 | total >= 100 |
total > 100 |
| 9 | EqualityOperator | 6 | total >= 100 |
total < 100 |
| 10 | BlockStatement | 6 | { fee = 0; } |
{} |
Other mutators you'll often see: LogicalOperator (a && b becomes a || b), BooleanLiteral (true becomes false), StringLiteral ("hello" becomes "") and UpdateOperator (i++ becomes i--).
100% coverage, a score of only 60%
Test A: calculateShipping(150, true) must be 0. Test B: calculateShipping(50, false) must be 20. These two tests bring coverage to 100%, branch coverage included. This table shows the value each mutant returns for the two tests:
| # | Mutant | Result A | Result B | Status |
|---|---|---|---|---|
| 1 | function body {} |
undefined |
killed | |
| 2 | if (true) on line 3 |
0 | 10 | killed |
| 3 | if (false) on line 3 |
0 | 20 | survived |
| 4 | line 3 block becomes {} |
0 | 20 | survived |
| 5 | fee * 2 |
0 | 20 | survived |
| 6 | if (true) on line 6 |
0 | 0 | killed |
| 7 | if (false) on line 6 |
10 | killed | |
| 8 | total > 100 |
0 | 20 | survived |
| 9 | total < 100 |
10 | killed | |
| 10 | line 6 block becomes {} |
10 | killed |
An empty Result B cell means Test A already killed that mutant, so Test B doesn't need to run. Out of 10 mutants, 6 are killed and 4 survive, so the mutation score is 60%, even though coverage is 100%.
- Mutants 3, 4 and 5 survive because all three change the members' half-price shipping on lines 3 and 4. Test A is a member, but the order is $150, so line 7 sets the fee to 0, whatever line 4 did. Test B isn't a member, so it isn't affected. Line 4 runs, but its result never reaches an
expect. - Mutant 8 survives because no test orders exactly $100. It's the
>bug that 100% coverage missed in Test Coverage & Strategy. - Add the test
calculateShipping(50, true), which must be 10: mutants 3, 4 and 5 are killed, and the score rises to 90%. Also addcalculateShipping(100, false), which must be 0: mutant 8 is killed too, and the score is 100%.
Running Stryker
Install Stryker (@stryker-mutator/core) and its link to Vitest (@stryker-mutator/vitest-runner) once, then run it:
npm install -D @stryker-mutator/core @stryker-mutator/vitest-runner
npx stryker run
You write its settings in the file stryker.config.json:
{
"testRunner": "vitest",
"mutate": ["src/**/*.js", "!src/**/*.test.js"],
"reporters": ["clear-text", "progress", "html"],
"thresholds": { "high": 80, "low": 60, "break": 50 }
}
mutatelists the files to mutate (the files Stryker changes). A!in front means that file is excluded, so your test files themselves aren't mutated.thresholds.break: 50: when the score is below 50, Stryker exits with exit code 1 (a sign of failure), so CI fails.highandlowonly set the colour of the score in the report.- The
clear-textreporter (one of the report formats) prints every mutant that survived (and every NoCoverage mutant) in the terminal. This is what it prints for mutant 8:
[Survived] EqualityOperator
src/shipping.js:6:7
- if (total >= 100) {
+ if (total > 100) {
Tests ran:
member, $150 order: free
not a member, $50 order: $20
The - line is the original code, and the + line is the mutant. Tests ran lists the tests that ran against that mutant. Read it as: "on line 6 column 7, >= can become > and no test fails". Add a test that tells the two apart: an order of exactly $100.
Tools for other languages: Infection for PHP, PIT or Pitest for Java, and mutmut for Python. Infection calls the mutation score MSI (mutation score indicator), and vendor/bin/infection --min-msi=80 fails when the MSI is below 80.
Exercise: runMutation
In the exercise you build a mini version of steps 2 and 3 above. Assume each test case (one input you try) expects exactly the result the original code gives. So a mutant is killed when at least one input makes the results of original and mutant differ. weakTest() and the two console.log lines below are already in the exercise's starting code:
function runMutation(original, mutant, testCases) {
const isKilled = testCases.some((input) => original(input) !== mutant(input));
return isKilled ? "killed" : "survived";
}
function weakTest() {
const original = (age) => age >= 18;
const mutant = (age) => age > 18;
return runMutation(original, mutant, [20]); // a weak test case
}
console.log(weakTest()); // survived
console.log(runMutation((age) => age >= 18, (age) => age > 18, [18, 20])); // killed
testCases.some(...)istruewhen at least one input meets the condition inside its brackets.original(input) !== mutant(input)compares the results of the two functions for the same input.- With
[20]:20 >= 18and20 > 18are bothtrue, so no result differs:"survived". - With
[18, 20]:18 >= 18istrue, but18 > 18isfalse. One differing result is enough:"killed". - Two functions whose results always agree, such as
(n) => n * 2as the original and the mutant, can't be told apart by any input:"survived".
⚠️ Wrong ideas about mutants and the score
- Thinking 100% coverage means strong tests. Coverage records the lines that ran. Mutation score measures whether a change on those lines gets noticed.
- Chasing a score of 100%. There are equivalent mutants: mutants whose behaviour is exactly the same as the original code. For example
return a > b ? a : bbecomingreturn a >= b ? a : b.>and>=only differ whenaequalsb, and then both versions return the same number. No test can kill this mutant. So pick a target below 100%, for example 75 to 85%. - Running it on every file on every commit. The tests run again for each mutant, so mutation testing can take dozens of times longer than a normal test run. Start with important code such as prices, payments and validation. Run it on a schedule, or use
npx stryker run --incrementalso only changed code is mutated again. - In the exercise, requiring every input to differ. One input whose result differs already kills the mutant. Use
some, notevery(which is onlytruewhen every input differs), and compare with!==.
TL;DR: Mutation testing tests your tests. The tool makes small changes to your code on purpose, one at a time (each changed version is called a mutant), then runs the tests against each mutant. If a test fails, the mutant is killed. If every test still passes, the mutant survived: the change went unnoticed, and your tests are weak there. Mutation score = caught mutants divided by all mutants. 100% coverage can still score only 60%, because a line that ran isn't necessarily a line whose result was checked. The tools are Stryker for JavaScript and TypeScript (npx stryker run), Infection for PHP, PIT for Java and mutmut for Python. Start with important code, and accept that equivalent mutants (mutants that behave the same as the original code) can't be killed. In the exercise, use some with !==: one input where the original and the mutant give different results means "killed".
⚡ Killed or survived
Meaning: Mutation testing tests your tests. The tool changes a small piece of your code on purpose (the changed version is called a mutant), then runs every test. A test fails: the mutant is killed. Every test still passes: the mutant survived, the change went unnoticed, and your tests are weak in that spot. Mutation score = caught mutants divided by all mutants.
⚡ 100% coverage, a score of only 60%
Guess first: calculateShipping(total, member) calculates the shipping fee, and orders from $100 ship free through if (total >= 100). The tests are calculateShipping(150, true) and calculateShipping(50, false), and coverage is 100%. Is the mutant total > 100 (>= swapped for >) killed or survived?
Survived. No test orders exactly $100, the only total where > and >= give different results.
Meaning: Those two tests kill only 6 of the 10 mutants of this code, so the mutation score is 60%. Add the test calculateShipping(100, false), which must be 0, and the > mutant is killed. A line that ran isn't necessarily a line whose result was checked.
⚡ runMutation in the exercise
Write:
function runMutation(original, mutant, testCases) {
const isKilled = testCases.some((input) => original(input) !== mutant(input));
return isKilled ? "killed" : "survived";
}
Meaning: In the exercise, runMutation compares the results of original and mutant for each input in testCases. One input whose result differs is enough to kill the mutant, so use some (one is enough) with !==, not every (all of them must).