Skip to main content

Testing and QA · Advanced · 26 min

Measure test quality with mutation testing in JavaScript using Stryker

By Padding · Updated 18 Nov 2026
Node.js 26 · StrykerJS 10.1.1 · Vitest 5.1.2 · checked on node:26

You will run StrykerJS against a pricing module whose tests already show 100 percent coverage, kill the mutants those tests miss, deal with an equivalent mutant, and finish with a scoped, incremental run and a break threshold that fails CI.

On this page

Coverage tells you which lines ran while the tests were running. It does not tell you whether any test would fail if one of those lines were wrong. A test that calls a function and checks nothing gives the same coverage as one that checks the exact answer.

Mutation testing measures the second thing. A tool makes small, deliberate changes to your code, one at a time: >= becomes >, + becomes -, a condition becomes true. Each changed copy is a mutant. Your tests run against every mutant. If a test fails, the mutant is killed: your tests noticed. If every test still passes, the mutant survived, and you have found a change to the code that your suite would let through.

In this tutorial you use StrykerJS, the mutation testing tool for JavaScript and TypeScript, with its Vitest runner. You start with a small pricing module and a test suite that reports 100 percent line and branch coverage. Stryker shows that 14 of its 47 mutants survive. You read the survivors, write sharper assertions that kill them, decide what to do about two mutants no test can kill, then make runs faster and add a threshold that fails the build when the score drops.

Step 1 · Set up a project with tests that look complete

Create a throwaway project and install Vitest, its coverage provider and Stryker, each at an exact version:

Bash
mkdir -p ~/mutation-testing-demo/src ~/mutation-testing-demo/test
cd ~/mutation-testing-demo
cat > package.json <<'JSON'
{
  "name": "mutation-testing-demo",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "vitest run",
    "mutate": "stryker run"
  }
}
JSON
npm install --save-dev --save-exact vitest@5.1.2 @vitest/coverage-v8@5.1.2 @stryker-mutator/core@10.1.1 @stryker-mutator/vitest-runner@10.1.1
cat > .gitignore <<'TXT'
node_modules/
coverage/
reports/
.stryker-tmp/
TXT

The packages take about 100 MB on disk. If you pay for data by the megabyte, install once and reuse the folder; nothing later in the tutorial downloads anything else.

Now the code under test. src/pricing.js prices a shop order. Amounts are whole minor units (kobo, cents, pence), so 50000 means 500.00 and there is no floating-point rounding in money. The shop's rules:

  • Ten or more of one item get 10 percent off that line.
  • An optional coupon takes 0 to 50 percent off the subtotal.
  • Delivery costs 1500, and is free when the subtotal is 50000 or more.
Bash
cd ~/mutation-testing-demo
cat > src/pricing.js <<'JS'
// Prices are whole minor units (kobo, cents, pence): 150000 means 1,500.00.
export const BULK_QUANTITY = 10;
export const BULK_DISCOUNT_PERCENT = 10;
export const FREE_DELIVERY_FROM = 50000;
export const DELIVERY_FEE = 1500;
export const MAX_COUPON_PERCENT = 50;

export function lineTotal(unitPrice, quantity) {
  if (!Number.isInteger(quantity) || quantity < 1) {
    throw new RangeError(`quantity must be a whole number of 1 or more, got ${quantity}`);
  }
  const gross = unitPrice * quantity;
  if (quantity >= BULK_QUANTITY) {
    return gross - Math.round((gross * BULK_DISCOUNT_PERCENT) / 100);
  }
  return gross;
}

export function priceOrder(lines, couponPercent = 0) {
  if (couponPercent < 0 || couponPercent > MAX_COUPON_PERCENT) {
    throw new RangeError(`coupon must be 0 to ${MAX_COUPON_PERCENT} percent, got ${couponPercent}`);
  }
  let subtotal = 0;
  for (const line of lines) {
    subtotal += lineTotal(line.unitPrice, line.quantity);
  }
  if (couponPercent > 0) {
    subtotal -= Math.round((subtotal * couponPercent) / 100);
  }
  const delivery = subtotal >= FREE_DELIVERY_FROM ? 0 : DELIVERY_FEE;
  return { subtotal, delivery, total: subtotal + delivery };
}
JS

Next, the kind of suite that gets written in a hurry. Every test passes, every line and branch runs, and several tests check almost nothing:

Bash
cd ~/mutation-testing-demo
cat > test/pricing.test.js <<'JS'
import { describe, expect, test } from 'vitest';
import { lineTotal, priceOrder } from '../src/pricing.js';

describe('lineTotal', () => {
  test('multiplies price by quantity', () => {
    expect(lineTotal(2000, 3)).toBe(6000);
  });

  test('gives a discount on bulk orders', () => {
    expect(lineTotal(2000, 12)).toBeLessThan(24000);
  });

  test('rejects a quantity of zero', () => {
    expect(() => lineTotal(2000, 0)).toThrow();
  });
});

describe('priceOrder', () => {
  test('adds up the lines', () => {
    const order = priceOrder([{ unitPrice: 2000, quantity: 2 }]);
    expect(order.total).toBeGreaterThan(0);
  });

  test('applies a coupon', () => {
    const order = priceOrder([{ unitPrice: 60000, quantity: 1 }], 10);
    expect(order.subtotal).toBe(54000);
  });

  test('rejects a coupon over the limit', () => {
    expect(() => priceOrder([], 80)).toThrow();
  });
});
JS
cat > vitest.config.js <<'JS'
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    include: ['test/**/*.test.js'],
    coverage: {
      provider: 'v8',
      include: ['src/**/*.js'],
      reporter: ['text-summary', 'json-summary'],
    },
  },
});
JS
npx vitest run --coverage

Check it worked

Vitest reports 6 passed, and the coverage summary under it shows 100% for statements, branches, functions and lines. By the usual measure this module is fully tested. Keep that number in mind for the next step.

Step 2 · Run Stryker for the first time

Stryker reads its settings from stryker.config.json in the project root. This one tells it to use the Vitest runner with your Vitest config, to mutate everything under src/, and to write four reports: a table in the terminal (clear-text), a progress bar, an HTML report and a JSON report.

Bash
cd ~/mutation-testing-demo
cat > stryker.config.json <<'JSON'
{
  "$schema": "./node_modules/@stryker-mutator/core/schema/stryker-schema.json",
  "testRunner": "vitest",
  "vitest": { "configFile": "vitest.config.js" },
  "mutate": ["src/**/*.js"],
  "reporters": ["clear-text", "progress", "html", "json"]
}
JSON
npx stryker run

Here is what happens during the run:

  1. Stryker copies the project into a sandbox folder, .stryker-tmp/, so your files are never edited.
  2. It instruments src/pricing.js with every mutant at once, each one switched off until it is needed.
  3. It runs the whole suite once with no mutant active (the dry run) and records which tests reach which mutant. The Vitest runner always does this per test.
  4. For each mutant it runs only the tests that reach it, and stops at the first failure.

On a laptop with only a few cores, add --concurrency 2 to keep the machine usable while it works. By default Stryker starts one test runner per logical core, minus one on machines with more than four.

Check it worked

The run ends with a table. The pricing.js row reads something like this:

Text
File        |  total | covered | # killed | # timeout | # survived | # no cov | # errors |
pricing.js  |  70.21 |   70.21 |       33 |         0 |         14 |        0 |        0 |

The mutation score is 70.21: 33 of 47 mutants were killed. The same code had 100 percent coverage. # no cov is 0 because every mutant sits on a line some test runs; the 14 survivors were all executed and still went unnoticed.

Step 3 · Read the surviving mutants

Above the table, Stryker prints each survivor with the original line, the mutated line and the tests that ran against it. One of them:

Text
[Survived] EqualityOperator
src/pricing.js:13:7
-     if (quantity >= BULK_QUANTITY) {
+     if (quantity > BULK_QUANTITY) {
Tests ran:
    lineTotal > multiplies price by quantity
    lineTotal > gives a discount on bulk orders

That mutant moves the bulk discount from 10 items to 11. Two tests ran against it and neither noticed, because neither tries exactly 10 items.

The terminal output gets long. The JSON report at reports/mutation/mutation.json holds the same results, so a short script can list every survivor on one line each:

Bash
cd ~/mutation-testing-demo
cat > survivors.mjs <<'JS'
// List the mutants that no test caught, then count mutants by status.
import { readFileSync } from 'node:fs';

const report = JSON.parse(readFileSync('reports/mutation/mutation.json', 'utf8'));
const counts = {};
for (const [path, file] of Object.entries(report.files)) {
  for (const mutant of file.mutants) {
    counts[mutant.status] = (counts[mutant.status] ?? 0) + 1;
    if (mutant.status === 'Survived' || mutant.status === 'NoCoverage') {
      const where = `${path}:${mutant.location.start.line}`;
      console.log(`${mutant.status.padEnd(10)} ${where.padEnd(18)} ${mutant.mutatorName.padEnd(22)} ${mutant.replacement}`);
    }
  }
}
console.log(Object.entries(counts).sort().map(([status, n]) => `${status}=${n}`).join(' '));
JS
node survivors.mjs

For a visual view, open reports/mutation/mutation.html in a browser. It shows the source with a marker on every mutant, coloured by status; selecting one shows the change.

Read the 14 survivors as a list of things your tests do not pin down. They fall into four groups:

  • Weak assertions. toBeLessThan(24000) accepts any discount, so mutants that turn / 100 into * 100 or * BULK_DISCOUNT_PERCENT into / BULK_DISCOUNT_PERCENT survive. toBeGreaterThan(0) on the total lets subtotal + delivery become subtotal - delivery.
  • Missing boundaries. Nothing tries exactly 10 items, exactly 50 percent off or a subtotal of exactly 50000, so >= and > swaps survive. No test checks the delivery amount: one test takes the free delivery branch but only asserts the subtotal, and the other only checks that the total is above 0. So the true, false and < mutants on the delivery line survive too.
  • Unchecked branches and messages. No test passes a negative coupon, so couponPercent < 0 || can become false ||. The two toThrow() calls accept any error, so emptying either message string survives.
  • Line 27. Two mutants change if (couponPercent > 0) into if (true) and if (couponPercent >= 0). Keep these in mind; they come back in a later step.

Check it worked

node survivors.mjs prints 14 lines starting Survived, then Killed=33 Survived=14. You can match each line to one of the four groups above.

Step 4 · Kill the survivors with sharper tests

Each survivor tells you what a better test must check. Replace the test file with one that asserts exact values, tries each boundary on both sides and checks error messages:

Bash
cd ~/mutation-testing-demo
cat > test/pricing.test.js <<'JS'
import { describe, expect, test } from 'vitest';
import { lineTotal, priceOrder } from '../src/pricing.js';

describe('lineTotal', () => {
  test('multiplies price by quantity below the bulk quantity', () => {
    expect(lineTotal(2000, 3)).toBe(6000);
    expect(lineTotal(2000, 9)).toBe(18000);
  });

  test('takes 10 percent off from exactly 10 items', () => {
    expect(lineTotal(2000, 10)).toBe(18000);
    expect(lineTotal(2000, 12)).toBe(21600);
  });

  test('rounds the bulk discount to the nearest minor unit', () => {
    expect(lineTotal(1005, 10)).toBe(9045);
  });

  test('rejects a quantity that is not a whole number of 1 or more', () => {
    expect(() => lineTotal(2000, 0)).toThrow(/quantity must be a whole number/);
    expect(() => lineTotal(2000, 1.5)).toThrow(RangeError);
  });
});

describe('priceOrder', () => {
  test('charges delivery on orders under the free delivery amount', () => {
    expect(priceOrder([{ unitPrice: 2000, quantity: 2 }])).toEqual({
      subtotal: 4000,
      delivery: 1500,
      total: 5500,
    });
  });

  test('delivers free from exactly 50000', () => {
    expect(priceOrder([{ unitPrice: 25000, quantity: 2 }])).toEqual({
      subtotal: 50000,
      delivery: 0,
      total: 50000,
    });
    expect(priceOrder([{ unitPrice: 49999, quantity: 1 }]).delivery).toBe(1500);
  });

  test('applies a coupon to the subtotal before deciding delivery', () => {
    expect(priceOrder([{ unitPrice: 50000, quantity: 1 }], 10)).toEqual({
      subtotal: 45000,
      delivery: 1500,
      total: 46500,
    });
  });

  test('accepts coupons from 0 to 50 percent', () => {
    expect(priceOrder([{ unitPrice: 2000, quantity: 1 }], 0).subtotal).toBe(2000);
    expect(priceOrder([{ unitPrice: 2000, quantity: 1 }], 50).subtotal).toBe(1000);
  });

  test('rejects coupons outside 0 to 50 percent', () => {
    expect(() => priceOrder([], 51)).toThrow(/coupon must be 0 to 50 percent/);
    expect(() => priceOrder([], -5)).toThrow(RangeError);
  });
});
JS
npx vitest run
npx stryker run
node survivors.mjs

A few of these tests are worth a closer look:

  • lineTotal(1005, 10) is 10050 gross with a discount of 1005, so it pins the exact sum. Any change to the arithmetic gives a different number.
  • lineTotal(2000, 1.5) throws only because of Number.isInteger. Quantity 0 alone cannot tell whether that check is there, since 0 < 1 throws anyway.
  • The coupon test uses a 50000 order that drops to 45000. It proves the coupon comes off before the delivery check, which is a business rule the old suite never stated.

Each assertion was written because a specific mutant showed a gap. That is the useful habit: a survivor is a question ("would anyone notice if this were >?"), and the test you add is the answer.

Check it worked

Vitest reports 9 passed. Stryker's table shows 45 killed and 2 survived, and node survivors.mjs lists only the two mutants on line 27.

Step 5 · Deal with the equivalent mutants

Look at the two that are left:

Text
Survived   src/pricing.js:27  ConditionalExpression  true
Survived   src/pricing.js:27  EqualityOperator       couponPercent >= 0

Both make the coupon line run when couponPercent is 0. With a 0 percent coupon it subtracts Math.round(0), which is 0. Negative coupons are rejected at the top of the function, so no input can reach line 27 with a value that makes the mutant behave differently. These are equivalent mutants: they change the code but not what it does. No test can kill them, and trying would waste your time.

You have two honest options:

  • Remove the code that makes them possible. Here the if exists only to skip subtracting zero. It adds nothing, so the clean fix is to delete it. An equivalent mutant often points at code like this.
  • Mark the line, with a reason. When the code must stay (a guard that avoids a slow call, for example), put // Stryker disable next-line ConditionalExpression,EqualityOperator: <why> on the line above. Stryker then reports those mutants as Ignored and leaves them out of the score. The comment switches off every mutant from the named mutators on that line, including ones a test could kill (here if (false) and couponPercent <= 0), so keep it narrow and write the reason down.

Take the first option. Rewrite priceOrder without the guard:

Bash
cd ~/mutation-testing-demo
cat > src/pricing.js <<'JS'
// Prices are whole minor units (kobo, cents, pence): 150000 means 1,500.00.
export const BULK_QUANTITY = 10;
export const BULK_DISCOUNT_PERCENT = 10;
export const FREE_DELIVERY_FROM = 50000;
export const DELIVERY_FEE = 1500;
export const MAX_COUPON_PERCENT = 50;

export function lineTotal(unitPrice, quantity) {
  if (!Number.isInteger(quantity) || quantity < 1) {
    throw new RangeError(`quantity must be a whole number of 1 or more, got ${quantity}`);
  }
  const gross = unitPrice * quantity;
  if (quantity >= BULK_QUANTITY) {
    return gross - Math.round((gross * BULK_DISCOUNT_PERCENT) / 100);
  }
  return gross;
}

export function priceOrder(lines, couponPercent = 0) {
  if (couponPercent < 0 || couponPercent > MAX_COUPON_PERCENT) {
    throw new RangeError(`coupon must be 0 to ${MAX_COUPON_PERCENT} percent, got ${couponPercent}`);
  }
  let subtotal = 0;
  for (const line of lines) {
    subtotal += lineTotal(line.unitPrice, line.quantity);
  }
  subtotal -= Math.round((subtotal * couponPercent) / 100);
  const delivery = subtotal >= FREE_DELIVERY_FROM ? 0 : DELIVERY_FEE;
  return { subtotal, delivery, total: subtotal + delivery };
}
JS
npx vitest run
npx stryker run
node survivors.mjs

Do not chase 100 percent as a goal in itself. On real code some equivalent mutants are not worth removing, and a score in the high 80s or 90s with every survivor explained is a strong suite. What matters is that you looked at each survivor and either added a test, changed the code or wrote down why it stays.

Check it worked

All 9 tests still pass, so removing the guard changed nothing a caller can see. Stryker reports a mutation score of 100.00 with 42 killed, and node survivors.mjs prints only Killed=42.

Step 6 · Make runs faster with --mutate and incremental mode

Mutation testing is slow by nature: it runs your tests once per mutant. This module has 42 mutants and finishes in seconds, but a real codebase can have tens of thousands. Two options keep runs short.

--mutate on the command line replaces the mutate setting for one run. It takes globs, and a file with a line range mutates only those lines. Lines 8 to 17 are lineTotal, so this run only creates mutants inside that function:

Bash
cd ~/mutation-testing-demo
npx stryker run --mutate "src/pricing.js:8-17"
node survivors.mjs

Use this while you work on one function: change it, add tests, run Stryker on just those lines.

Incremental mode works across runs. With --incremental, Stryker saves its results to reports/stryker-incremental.json. Next time, it diffs your source and test files against that file and reruns only the mutants whose code, or whose covering tests, changed. Run it twice:

Bash
cd ~/mutation-testing-demo
npx stryker run --incremental
npx stryker run --incremental

The first run finds no incremental file and runs everything. The second finds nothing changed and reuses every result.

Incremental mode only sees changes to source and test files. A dependency upgrade, an environment variable or a changed fixture file does not trigger a rerun, so add --force to rerun everything in scope when you suspect a stale result. In CI, keep the incremental file between runs with your CI service's cache, and do a full run (no --incremental) on a schedule, for example nightly.

Check it worked

The --mutate run reports 19 mutants, all killed, and only pricing.js lines 8 to 17 appear in the report. The second --incremental run prints an incremental report ending in a line like Result: 42 of 42 mutant result(s) are reused. and finishes faster than the first.

Step 7 · Fail the build when the score drops

A score that nobody checks drifts down. Stryker's thresholds setting fixes that. high and low only colour the report (green above high, red below low). break is the one that matters for CI: when the final score is below it, Stryker exits with code 1, and any CI system marks the job as failed.

Rewrite the config with thresholds. A break of 90 suits this small module; on an existing codebase, start a little below the score you have today and raise it as you improve the suite.

Bash
cd ~/mutation-testing-demo
cat > stryker.config.json <<'JSON'
{
  "$schema": "./node_modules/@stryker-mutator/core/schema/stryker-schema.json",
  "testRunner": "vitest",
  "vitest": { "configFile": "vitest.config.js" },
  "mutate": ["src/**/*.js"],
  "reporters": ["clear-text", "progress", "html", "json"],
  "thresholds": { "high": 90, "low": 75, "break": 90 }
}
JSON
npm run mutate

That passes. Now do what happens on a busy team: add a module with no tests. src/delivery.js turns distance into delivery days:

Bash
cd ~/mutation-testing-demo
cat > src/delivery.js <<'JS'
// Working days to deliver, by road distance from the warehouse.
export function deliveryDays(distanceKm) {
  if (distanceKm <= 15) {
    return 1;
  }
  if (distanceKm <= 120) {
    return 2;
  }
  return 4;
}
JS
npm run mutate || echo "Stryker failed the run with exit code $?"

The new file adds 11 mutants that no test reaches (# no cov). They count against the score, which drops to 79.25, and Stryker logs Final mutation score 79.25 under breaking threshold 90, setting exit code to 1 (failure). Add tests that try each distance boundary on both sides:

Bash
cd ~/mutation-testing-demo
cat > test/delivery.test.js <<'JS'
import { expect, test } from 'vitest';
import { deliveryDays } from '../src/delivery.js';

test.each([
  [0, 1],
  [15, 1],
  [16, 2],
  [120, 2],
  [121, 4],
])('%i km takes %i working day(s)', (distanceKm, days) => {
  expect(deliveryDays(distanceKm)).toBe(days);
});
JS
npm run mutate
node survivors.mjs

In CI, run npm run mutate as its own job after the unit tests pass. A full run on a large codebase can take long enough that you only want it on the main branch or nightly, with --incremental or a --mutate list of changed files on pull requests.

Check it worked

With delivery.js untested, the run ends with the break message and the shell prints Stryker failed the run with exit code 1. After adding test/delivery.test.js, the table shows 53 killed across both files, the log says the score of 100.00 is greater than or equal to the break threshold, and the command exits 0.

Step 8 · Remove the demo project

When you are done, delete the folder. It holds everything the tutorial created, including node_modules, the reports and the incremental file.

Bash
rm -rf ~/mutation-testing-demo

Check it worked

ls ~/mutation-testing-demo reports that there is no such file or directory.

Next steps

  • See where coverage numbers mislead and how to use them well in /tutorials/measure-code-coverage-without-chasing-100-percent.
  • Run the same process on Python code in /tutorials/run-mutation-testing-on-python-with-mutmut.
  • Put the Stryker break threshold alongside linting and tests in /tutorials/build-a-ci-quality-gate-for-pull-requests.
  • Apply sharper assertions to component tests in /tutorials/test-ui-code-with-vitest-and-testing-library.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.