Skip to content
jshacks.dev
Testing

Write a mutation test run with Stryker

Run StrykerJS with the Vitest runner to change your source on purpose and find which tests still pass when they should fail.

1 min read
Summarize in AI

Coverage tells you a line ran, not that a test would notice if it were wrong. Mutation testing changes the code and checks whether any test fails.

src/discount.jsJavaScript
export function discount(qty) {
  return qty >= 10 ? 0.9 : 1;
}
src/discount.test.jsJavaScript
import { test, expect } from 'vitest';
import { discount } from './discount.js';

test('bulk orders get 10% off', () => {
  expect(discount(20)).toBe(0.9);
  expect(discount(1)).toBe(1);
});
stryker.config.jsonJSON
{
  "testRunner": "vitest",
  "mutate": ["src/**/*.js", "!src/**/*.test.js"],
  "reporters": ["clear-text"]
}

Install @stryker-mutator/core and @stryker-mutator/vitest-runner, then run npx stryker run. One of the reported mutants, trimmed:

Text
[Survived] EqualityOperator
src/discount.js:2:10
-   return qty >= 10 ? 0.9 : 1;
+   return qty > 10 ? 0.9 : 1;

Stryker rewrote >= to > and the tests still passed, because nothing tests a quantity of exactly 10. Adding expect(discount(10)).toBe(0.9) kills that mutant. The operators it applies are listed in the Stryker mutator docs.

A full run executes the tests once per mutant, so point mutate at the code that matters, or run it nightly instead of on every push.

Taggedstryker
Share

More snippets

Debugging

Debug a single Vitest test in VS Code

Run one Vitest file under the VS Code debugger with a launch configuration that passes the open file, so breakpoints in tests and source work. Vitest 3.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.