Mutation Testing

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…

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

  1. The mutation testing tool changes one small piece of your code, for example >= into >. This changed version of the code is called a mutant.
  2. All the tests run against that mutant.
  3. A test fails: the mutant is killed. Your tests caught the change.
  4. 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.
  5. 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%.

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 }
}
[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

⚠️ Wrong ideas about mutants and the score

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).

What you will learn