On this page

Custom mutators

Each mutator makes one kind of change and stands for one kind of mistake. When your code can go wrong in a way that no built-in mutator stands for, write your own.

This guide writes date-setter, which calls the setter of a neighboring unit of a date, such as setMinutes in place of setHours. By the end, the mutator runs with your tests, has an option and skips calls on objects that are not dates. It lives in a TypeScript file of your project, so you need Node.js 22.18 or later, or the jiti package, as for a TypeScript configuration.

Pick a mistake

This function of a sample shop, in src/pickup.ts, sets the pickup time two hours after the order:

export function getPickupTime(ordered: Date): Date {
  let pickup = new Date(ordered)
  pickup.setHours(pickup.getHours() + 2)
  return pickup
}

With setMinutes in place of setHours, an order at 9:30 gets its pickup at 9:11, not 11:30. The test checks only the day, so it passes with either method:

it('keeps the pickup on the day of the order', () => {
  let ordered = new Date(2026, 4, 12, 9, 30)
  expect(getPickupTime(ordered).getDate()).toBe(12)
})

No built-in mutator swaps one date method for another. date-setter adds this mutant:

pickup.setHours(pickup.getHours() + 2) pickup.setMinutes(pickup.getHours() + 2)

Find the nodes

Mootant parses each file into a tree of nodes in the ESTree format, and a mutator names the types of nodes it visits. Here are the nodes of the changed line, each with the condition that finds it:

pickup.setHours(pickup.getHours() + 2)
node.type === 'CallExpression'

date-setter visits CallExpression nodes. It changes a call when the callee is a MemberExpression whose property is an Identifier with the name of a date setter. The property must not be computed: in date[setHours](1), setHours is a variable, and a changed name would make a different mistake.

Write the mutator

Create mootant/dates.ts. The file exports a plugin with the mutator:

import type { Mutator, Plugin } from 'mootant'

let units = [
  'FullYear',
  'Month',
  'Date',
  'Hours',
  'Minutes',
  'Seconds',
  'Milliseconds',
]

let swaps = new Map<string, string>()
for (let [index, unit] of units.entries()) {
  let other = units[index + 1] ?? units[index - 1]
  swaps.set(`set${unit}`, `set${other}`)
  swaps.set(`setUTC${unit}`, `setUTC${other}`)
}

let dateSetter: Mutator = {
  meta: {
    description: 'Swaps a date method for the one of a neighboring unit.',
  },
  create(context) {
    return {
      CallExpression(node) {
        let { callee } = node
        if (
          callee.type !== 'MemberExpression' ||
          callee.computed ||
          callee.property.type !== 'Identifier'
        ) {
          return []
        }
        let swap = swaps.get(callee.property.name)
        if (swap === undefined) {
          return []
        }
        let focus = {
          start: callee.property.start,
          end: callee.property.end,
          text: swap,
        }
        let target = context.syntax.getChainRoot(node) ?? node
        return [
          {
            text: context.sourceCode.editText(target, [focus]),
            node: target,
            focus,
          },
        ]
      },
    }
  },
}

export default {
  mutators: {
    'date-setter': dateSetter,
  },
} satisfies Plugin

swaps gives each setter the one of the next smaller unit: setFullYear becomes setMonth, setHours becomes setMinutes, and setMilliseconds, the last, becomes setSeconds. The setUTC setters swap the same way.

The mutator has two parts:

  • meta.description: one sentence about the mistake. The HTML report and --json --verbose show it.
  • create(context): Mootant calls it once per file, and for a Vue or Svelte file once per script block and once for the template. It returns visitors, functions keyed by node type, and each visitor returns a list of replacements. An empty list makes no mutant.

A replacement has three fields here:

  • node: the node that the mutant replaces.
  • text: the code written in its place. context.sourceCode.editText builds it from the code of the node and edits inside it.
  • focus: the edit that reports show, setHours → setMinutes, in place of the whole call.

Which node to replace

Mootant switches a mutant on inside your code, so a replacement must take a whole expression whose value is used, or a whole statement. The callee pickup.setHours is neither, and replacing node.callee gives this error:

✖ src/pickup.ts:3:3: Mutator "dates/date-setter" cannot replace a MemberExpression node in a position where Mootant cannot switch a mutant on. [mutator-error]

That’s why the mutator replaces the whole call and puts the change in focus. In an optional chain, such as date?.setHours(1), the call is part of the chain: context.syntax.getChainRoot(node) returns the chain, and the mutator replaces it.

Turn it on

Add the plugin to mootant.config.ts and turn the mutator on. Its id is the namespace of the plugin, a slash and its name:

import { defineConfig } from 'mootant'

import dates from './mootant/dates.ts'

export default defineConfig({
  mutators: {
    'dates/date-setter': 'on',
  },
  plugins: { dates },
})

Keep the .ts extension: Node.js resolves a relative import only by its full name. TypeScript accepts it with allowImportingTsExtensions.

list shows the mutants without running tests, so run it after each change to the mutator:

npx mootant list src
● mootant list src                                            preset recommended

mutants         4 in 1 file

src/pickup.ts
  3:10  dates/date-setter    setHours → setMinutes                          dpca
  3:19  arithmetic-operator  pickup.getHours() + 2 → pickup.getHours() - 2  rfpn
  3:39  number-literal       2 → 3                                          nvj4
  4:10  return-value         pickup → undefined                             wcs1

Kill the mutant

Run the tests against the mutant. Take its id from your list output, here dpca:

npx mootant run src --mutant dpca
● mootant run src --mutant dpca                   vitest 5.1.2

dry run         1 test in 0.2s
mutants         1 in 1 file
time            0.6s (start 0.2s, dry run 0.2s, isolated 0.1s)

killed          0
survived        1
timeout         0
no coverage     0
score           0%

survived 1

src/pickup.ts
  3:10  dates/date-setter  dpca
    - pickup.setHours(pickup.getHours() + 2)
    + pickup.setMinutes(pickup.getHours() + 2)
    test: test/pickup.test.ts

re-check one: mootant run src --mutant dpca

The mutant survives because the test reads only the day. Add a test that reads the hour:

it('sets the pickup two hours after the order', () => {
  let ordered = new Date(2026, 4, 12, 9, 30)
  expect(getPickupTime(ordered).getHours()).toBe(11)
})

Run the same command again: Mootant reports the mutant as killed, with a score of 100%.

Add an option

Code can also read the wrong unit, as in getMinutes() for getHours(). The option getters makes date-setter swap getters too. It is off by default, so users turn it on when they want these mutants.

Declare the type of the options and their defaults:

let dateSetter: Mutator<{ getters: boolean }> = {
  meta: {
    description: 'Swaps a date method for the one of a neighboring unit.',
    defaultOptions: { getters: false },
  },

Add the getters to swaps:

for (let [index, unit] of units.entries()) {
  let other = units[index + 1] ?? units[index - 1]
  for (let prefix of ['get', 'getUTC', 'set', 'setUTC']) {
    swaps.set(`${prefix}${unit}`, `${prefix}${other}`)
  }
}

And read the option from context.options in the visitor:

let { name } = callee.property
let swap = swaps.get(name)
if (
  swap === undefined ||
  (name.startsWith('get') && !context.options.getters)
) {
  return []
}

Users set the option in mutators, and Mootant merges it over the defaults:

export default defineConfig({
  mutators: {
    'dates/date-setter': ['on', { getters: true }],
  },
  plugins: { dates },
})

Now pickup.getHours() gets a mutant too: getHours → getMinutes.

Skip calls on other classes

date-setter goes by the name of the method, so it also changes setHours of an object that is not a date:

export function createPickupInput(hours: number): TimeInput {
  let input = new TimeInput()
  input.setHours(hours)
  return input
}

TimeInput has its own setHours, and setMinutes in its place tells nothing about how the code handles dates. When the receiver is a local made with new of another class, the mutator still returns the replacement, but with skip. A skipped replacement never becomes a mutant, and list --skipped shows it with its reason.

This function finds the class. context.sourceCode.getBinding returns the declaration of a local:

import type { Mutator, Plugin, SourceCode, AST } from 'mootant'

function getClassName(
  receiver: AST.Expression,
  sourceCode: SourceCode,
): string | null {
  if (receiver.type !== 'Identifier') {
    return null
  }
  let binding = sourceCode.getBinding(receiver)
  if (
    binding?.declaration.type !== 'VariableDeclarator' ||
    binding.writes.length > 0
  ) {
    return null
  }
  let { init } = binding.declaration
  if (init?.type !== 'NewExpression' || init.callee.type !== 'Identifier') {
    return null
  }
  return init.callee.name
}

The visitor adds skip to the replacement:

let className = getClassName(callee.object, context.sourceCode)
return [
  {
    text: context.sourceCode.editText(target, [focus]),
    node: target,
    focus,
    ...(className !== null &&
      className !== 'Date' && {
        skip: {
          reason: `the receiver is a ${className}, not a Date`,
          rule: 'not-a-date',
        },
      }),
  },
]

skip names a rule. Declare it in skipRules of the plugin, with its category and whether it rests on a guess. This rule is a guess, since a class can extend Date:

export default {
  skipRules: {
    'not-a-date': { category: 'noise', heuristic: true },
  },
  mutators: {
    'date-setter': dateSetter,
  },
} satisfies Plugin

Reports show the rule as dates/not-a-date:

npx mootant list src/pickup-input.ts --skipped
● mootant list src/pickup-input.ts --skipped          preset recommended

mutants         2 in 1 file
skipped         1: 1 noise

src/pickup-input.ts
  5:3   statement-removal  input.setHours(hours) → ;  6nxe
  6:10  return-value       input → undefined          c738

skipped:

src/pickup-input.ts
  5:9  dates/date-setter  setHours → setMinutes  noise  dates/not-a-date
       the receiver is a TimeInput, not a Date

skip can also name a built-in rule. Mootant looks for the rule in the plugin first, then among its own. A name that is in neither place, such as the typo not-date, gives an error:

✖ src/pickup-input.ts:5:3: Mutator "dates/date-setter" returned a skip with the unknown rule "not-date". Did you mean "not-a-date"? [mutator-error]
The whole mootant/dates.ts
import type { Mutator, Plugin, SourceCode, AST } from 'mootant'

let units = [
  'FullYear',
  'Month',
  'Date',
  'Hours',
  'Minutes',
  'Seconds',
  'Milliseconds',
]

let swaps = new Map<string, string>()
for (let [index, unit] of units.entries()) {
  let other = units[index + 1] ?? units[index - 1]
  for (let prefix of ['get', 'getUTC', 'set', 'setUTC']) {
    swaps.set(`${prefix}${unit}`, `${prefix}${other}`)
  }
}

function getClassName(
  receiver: AST.Expression,
  sourceCode: SourceCode,
): string | null {
  if (receiver.type !== 'Identifier') {
    return null
  }
  let binding = sourceCode.getBinding(receiver)
  if (
    binding?.declaration.type !== 'VariableDeclarator' ||
    binding.writes.length > 0
  ) {
    return null
  }
  let { init } = binding.declaration
  if (init?.type !== 'NewExpression' || init.callee.type !== 'Identifier') {
    return null
  }
  return init.callee.name
}

let dateSetter: Mutator<{ getters: boolean }> = {
  meta: {
    description: 'Swaps a date method for the one of a neighboring unit.',
    defaultOptions: { getters: false },
  },
  create(context) {
    return {
      CallExpression(node) {
        let { callee } = node
        if (
          callee.type !== 'MemberExpression' ||
          callee.computed ||
          callee.property.type !== 'Identifier'
        ) {
          return []
        }
        let { name } = callee.property
        let swap = swaps.get(name)
        if (
          swap === undefined ||
          (name.startsWith('get') && !context.options.getters)
        ) {
          return []
        }
        let focus = {
          start: callee.property.start,
          end: callee.property.end,
          text: swap,
        }
        let target = context.syntax.getChainRoot(node) ?? node
        let className = getClassName(callee.object, context.sourceCode)
        return [
          {
            text: context.sourceCode.editText(target, [focus]),
            node: target,
            focus,
            ...(className !== null &&
              className !== 'Date' && {
                skip: {
                  reason: `the receiver is a ${className}, not a Date`,
                  rule: 'not-a-date',
                },
              }),
          },
        ]
      },
    }
  },
}

export default {
  skipRules: {
    'not-a-date': { category: 'noise', heuristic: true },
  },
  mutators: {
    'date-setter': dateSetter,
  },
} satisfies Plugin

Check the mutator

A test of your product shows that a mutant can be killed, not that the mutator changes the right calls. Put the calls it must handle in one file outside src, such as mootant/cases.ts:

class TimeInput {
  hours = 0

  setHours(hours: number): void {
    this.hours = hours
  }
}

let setHours = 'setHours' as const

export function callSetter(date: Date, hours: number): number {
  return date.setHours(hours)
}

export function callSetterIfAny(
  date: Date | undefined,
  hours: number,
): number | undefined {
  return date?.setHours(hours)
}

export function callSetterByName(date: Date, hours: number): number {
  return date[setHours](hours)
}

export function callGetter(date: Date): number {
  return date.getHours()
}

export function callOtherClass(hours: number): TimeInput {
  let input = new TimeInput()
  input.setHours(hours)
  return input
}

The test below expects the configuration from Add an option, with getters on. It runs list on the file and keeps the changes of date-setter: each has a focus and a line, and a skipped change also has its rule:

import { execSync } from 'node:child_process'
import { expect, it } from 'vitest'

interface Change {
  focus: { replacement: string; original: string }
  mutator: string
  rule?: string
  line: number
}

it('swaps date methods and skips other classes', () => {
  let output = execSync('npx mootant list mootant/cases.ts --skipped --json', {
    encoding: 'utf8',
  })
  let report = JSON.parse(output) as { skipped: Change[]; mutants: Change[] }
  let changes = [...report.mutants, ...report.skipped]
    .filter(change => change.mutator === 'dates/date-setter')
    .map(({ focus, line, rule }) =>
      [line, focus.original, '→', focus.replacement, rule].join(' ').trim(),
    )
  expect(changes).toEqual([
    '12 setHours → setMinutes',
    '19 setHours → setMinutes',
    '27 getHours → getMinutes',
    '32 setHours → setMinutes dates/not-a-date',
  ])
})

Line 23, date[setHours](hours), gets no change. Without the check of callee.computed, it gets setHours → setMinutes, and the test fails.

To use date-setter in other projects, publish the plugin as a package, as Plugins shows.

Reference

Mootant exports the types of mutators from mootant, as import type: for example Mutator, MutatorContext, Replacement, SourceCode, TypeHints, and AST for the nodes, such as AST.CallExpression. Their comments describe each method.

meta

FieldWhat it does
descriptionOne sentence about the mistake that the mutator stands for. Required
defaultOptionsOptions of the mutator when the configuration gives none. Options from the configuration are merged over them, key by key
countsForSolitaryWhether the mutants of the mutator count for the solitary rule. true when omitted: in recommended, the date-setter mutant drops the removal of pickup.setHours(…) as coarse

context

PropertyWhat it gives
optionsOptions of the mutator, merged over meta.defaultOptions
settingsSettings of the preset, such as loggers and timeouts
sourceCodeThe text, comments and tree of the file, with helpers such as getText, getParent, getBinding and editText
syntaxAnswers about the position of a node, such as getChainRoot and getEnclosingFunction
hintsWhat Mootant knows about the runtime type of an expression: canBe, cannotBe, isOnly and getType
isEnabled(id)Whether the preset turned on the mutator with this full id
isActive(id, node)Whether a mutant of that mutator that replaces the node will run: the mutator is on, and no ignore comment covers the mutant
filePath of the file as reports print it
idFull id of the running mutator, such as dates/date-setter

Replacement

FieldWhat it does
nodeNode that the mutant replaces: an expression whose value is used, or a statement
textCode written in place of the node
focusEdit inside the node that reports show in place of the whole node
skipMakes the replacement a skipped change: rule and reason, by for the mutant that makes it redundant, and heuristic for a guess that the rule does not make by itself
solitaryNodes whose whole effect a coarse mutant removes. The mutant is dropped when a finer one lies inside them