UNPKG

23.6 kBMarkdownView Raw
1[![Mutation testing badge](https://img.shields.io/endpoint?style=flat&url=https%3A%2F%2Fbadge-api.stryker-mutator.io%2Fgithub.com%2Fstryker-mutator%2Fstryker%2Fmaster%3Fmodule%3Dcore)](https://dashboard.stryker-mutator.io/reports/github.com/stryker-mutator/stryker/master?module=core)
2[![Build Status](https://github.com/stryker-mutator/stryker/workflows/CI/badge.svg)](https://github.com/stryker-mutator/stryker/actions?query=workflow%3ACI+branch%3Amaster)
3[![NPM](https://img.shields.io/npm/dm/@stryker-mutator/core.svg)](https://www.npmjs.com/package/@stryker-mutator/core)
4[![Node version](https://img.shields.io/node/v/@stryker-mutator/core.svg)](https://img.shields.io/node/v/@stryker-mutator/core.svg)
5[![Slack Chat](https://img.shields.io/badge/slack-chat-brightgreen.svg?logo=slack)](https://join.slack.com/t/stryker-mutator/shared_invite/enQtOTUyMTYyNTg1NDQ0LTU4ODNmZDlmN2I3MmEyMTVhYjZlYmJkOThlNTY3NTM1M2QxYmM5YTM3ODQxYmJjY2YyYzllM2RkMmM1NjNjZjM)
6
7![Stryker](https://github.com/stryker-mutator/stryker/raw/master/stryker-80x80.png)
8
9# Stryker
10*Professor X: For someone who hates mutants... you certainly keep some strange company.*
11*William Stryker: Oh, they serve their purpose... as long as they can be controlled.*
12
13## Introduction
14For an introduction to mutation testing and Stryker's features, see [stryker-mutator.io](https://stryker-mutator.io/).
15
16## Getting started
17
18Please follow the [quickstart on the website](https://stryker-mutator.io/stryker/quickstart).
19
20For small js projects, you can try the following command:
21
22```
23npm install --save-dev @stryker-mutator/core
24# Only for small projects:
25npx stryker run
26```
27
28It will run stryker with default values:
29
30* Uses `npm test` as your test command
31* Searches for files to mutate in the `lib` and `src` directories
32
33## Usage
34
35```sh
36$ npx stryker <command> [options] [configFile]
37```
38
39The main `command` for Stryker is `run`, which kicks off mutation testing.
40
41Although Stryker can run without any configuration, it is recommended to configure it when you can, as it can greatly improve performance of the mutation testing process. By default, Stryker will look for a `stryker.conf.js` or `stryker.conf.json` file in the current working directory (if it exists). This can be overridden by specifying a different file as the last parameter.
42
43Before your first run, we recommend you try the `init` command, which helps you to set up this config file and install any missing packages needed for your specific configuration. We recommend you verify the contents of the configuration file after this initialization, to make sure everything is setup correctly. Of course, you can still make changes to it, before you run Stryker for the first time.
44
45The following is an example `stryker.conf.json` file. It specifies running mocha tests with the mocha test runner.
46
47```json
48{
49 "$schema": "https://raw.githubusercontent.com/stryker-mutator/stryker/master/packages/api/schema/stryker-core.json",
50 "mutate": [
51 "src/**/*.js",
52 "!src/index.js"
53 ],
54 "testRunner": "mocha",
55 "reporters": ["progress", "clear-text", "html"],
56 "coverageAnalysis": "perTest"
57}
58```
59
60As a `stryker.conf.js` file this looks like this:
61```javascript
62/**
63* @type {import('@stryker-mutator/api/core').StrykerOptions}
64*/
65module.exports = {
66 mutate: [
67 'src/**/*.js',
68 '!src/index.js'
69 ],
70 testRunner: 'mocha',
71 reporters: ['progress', 'clear-text', 'html'],
72 coverageAnalysis: 'perTest'
73};
74```
75
76Make sure you *at least* specify the `testRunner` options when mixing the config file and/or command line options.
77
78## Command-line interface
79Stryker can also be installed, configured and run using the [Stryker-CLI](https://github.com/stryker-mutator/stryker-cli). If you plan on using Stryker in more projects, the Stryker-CLI is the easiest way to install, configure and run Stryker for your project.
80
81You can install the Stryker-CLI using:
82
83```bash
84$ npm install -g stryker-cli
85```
86
87The Stryker-CLI works by passing received commands to your local Stryker installation. If you don't have Stryker installed yet, the Stryker-CLI will help you with your Stryker installation. This method allows us to provide additional commands with updates of Stryker itself.
88
89## Supported mutators
90
91See our website for the [list of currently supported mutators](https://stryker-mutator.io/mutators.html).
92
93## Configuration
94
95All configuration options can either be set via the command line or via a config file.
96
97`files` and `mutate` both support globbing expressions using [node glob](https://github.com/isaacs/node-glob).
98This is the same globbing format you might know from [Grunt](https://github.com/gruntjs/grunt) or [Karma](https://github.com/karma-runner/karma).
99
100You can *ignore* files by adding an exclamation mark (`!`) at the start of an expression.
101
102### Available Options
103* [allowConsoleColors](#allowConsoleColors)
104* [buildCommand](#buildCommand)
105* [cleanTempDir](#cleanTempDir)
106* [commandRunner](#commandRunner)
107* [coverageAnalysis](#coverageAnalysis)
108* [dashboard.*](#dashboard)
109* [fileLogLevel](#fileLogLevel)
110* [files](#files-string)
111* [logLevel](#logLevel)
112* [maxConcurrentTestRunners](#maxConcurrentTestRunners)
113* [mutate](#mutate)
114* [mutator](#mutator)
115* [plugins](#plugins)
116* [reporters](#reporters)
117* [sandbox.fileHeaders](#sandbox.fileHeaders)
118* [sandbox.stripComments](#sandbox.stripComments)
119* [symlinkNodeModules](#symlinkNodeModules)
120* [tempDirName](#tempDirName)
121* [testRunner](#testRunner)
122* [thresholds](#thresholds)
123* [timeoutFactor](#timeoutFactor)
124* [timeoutMS](#timeoutMS)
125
126<a name="allowConsoleColors"></a>
127### `allowConsoleColors` [`boolean`]
128
129Default: `true`
130Command line: `--allowConsoleColors true`
131Config file: `allowConsoleColors: true`
132
133The `allowConsoleColors` value indicates whether Stryker should use colors in console.
134
135<a name="buildCommand"></a>
136### `buildCommand` [`string`]
137
138Default: `undefined`
139Command line: `[-b|--buildCommand] "npm run build"`
140Config file: `buildCommand: 'npm run build'`
141
142Configure a build command to run after mutating the code, but before mutants are tested. This is generally used to transpile your code before testing.
143Only configure this if your test runner doesn't take care of this already and you're not using just-in-time transpiler like `babel/register` or `ts-node`.
144
145<a name="cleanTempDir"></a>
146### `cleanTempDir` [`boolean`]
147
148Default: `true`
149Command line: `--cleanTempDir false`
150Config file: `cleanTempDir: false`
151
152Choose whether or not to clean the temp dir (which is ".stryker-tmp" inside the current working directory by default) after a successful run.
153The temp dir will never be removed when the run failed for some reason (for debugging purposes).
154
155<a name="commandRunner"></a>
156### `commandRunner` [`object`]
157
158Default: `{ command: 'npm test' }`
159Command line: *none*
160Config file: `commandRunner: { command: 'npm run mocha' }`
161
162With `commandRunner`, you can specify the command to execute for running tests.
163
164<a name="coverageAnalysis"></a>
165### `coverageAnalysis` [`string`]
166
167Default: `off`
168Command line: `--coverageAnalysis perTest`
169Config file: `coverageAnalysis: 'perTest'`
170
171With `coverageAnalysis` you specify which coverage analysis strategy you want to use.
172
173Stryker can analyse code coverage results. This can potentially speed up mutation testing a lot, as only the tests covering a
174particular mutation are tested for each mutant.
175This does *not* influence the resulting mutation testing score. It only improves performance.
176
177The possible values are:
178
179* **off**: Stryker will not determine the code covered by tests during the initial test run phase. All tests will be executed for each mutant
180during the mutation testing phase.
181
182* **all**: Stryker will determine the code covered by all tests during the initial test run phase. Only mutants actually covered by your
183test suite are tested during the mutation testing phase. This setting requires your test runner to be able to report the code coverage back to Stryker.
184Currently, only the `stryker-mocha-runner` and the `stryker-karma-runner` do this.
185
186* **perTest**: Stryker will determine the code covered by your test per executed test during the initial test run phase. Only mutants actually covered by your
187test suite are tested during the mutation testing phase.
188Only the tests that cover a particular mutant are tested for each one. This requires your tests to be able to run independently of each other and in random order.
189 before and after each test, as well as test filtering.
190 Currently all test runner plugins, except for `@stryker-mutator/jest-runner`) support this feature.
191
192<a name="dashboard"></a>
193### `dashboard` [`DashboardOptions`]
194
195Default: `{ baseUrl: 'https://dashboard.stryker-mutator.io/api/reports', reportType: 'mutationScore' }`
196Command line: `--dashboard.project github.com/my-org/my-project --dashboard.version branch-or-tag --dashboard.module my-module --dashboard.baseUrl https://dashboard.stryker-mutator.io/api/reports --dashboard.reportType full`
197Config file: `{ project: 'github.com/my-org/my-project', version: 'branch-or-tag', module: 'my-module', baseUrl: 'https://dashboard.stryker-mutator.io/api/reports', reportType: 'full' }`
198
199Settings for the `dashboard` [reporter](#reporters). See the [stryker handbook for more info](https://github.com/stryker-mutator/stryker-handbook/blob/master/dashboard.md)
200
201<a name="fileLogLevel"></a>
202### `fileLogLevel` [`string`]
203
204Default: `off`
205Command line: `--fileLogLevel info`
206Config file: `fileLogLevel: 'info'`
207
208Set the log level that Stryker uses to write to the "stryker.log" file. Possible values: `off`, `fatal`, `error`, `warn`, `info`, `debug` and `trace`
209
210<a name="files-string"></a>
211### `files` [`string[]`]
212
213Default: result of `git ls-files --others --exclude-standard --cached --exclude .stryker-tmp`
214Command line: `[--files|-f] src/**/*.js,a.js,test/**/*.js`
215Config file: `files: ['src/**/*.js', '!src/**/index.js', 'test/**/*.js']`
216
217With `files`, you can choose which files should be included in your test runner sandbox.
218This is normally not needed as it defaults to all files not ignored by git.
219Try it out yourself with this command: `git ls-files --others --exclude-standard --cached --exclude .stryker-tmp`.
220
221If you do need to override `files` (for example: when your project does not live in a git repository),
222you can override the files here.
223
224When using the command line, the list can only contain a comma separated list of globbing expressions.
225When using the config file you can provide an array with `string`s
226
227You can *ignore* files by adding an exclamation mark (`!`) at the start of an expression.
228
229<a name="logLevel"></a>
230### `logLevel` [`string`]
231
232Default: `info`
233Command line: `--logLevel info`
234Config file: `logLevel: 'info'`
235
236
237 Set the log level that Stryker uses to write to the console. Possible values: `off`, `fatal`, `error`, `warn`, `info`, `debug` and `trace`
238
239 *Note*: Test runners are run as child processes of the Stryker Node process. All output (stdout) of the `testRunner` is logged as `trace`.
240 Thus, to see logging output from the test runner set the `logLevel` to `all` or `trace`.
241
242<a name="maxConcurrentTestRunners"></a>
243### `maxConcurrentTestRunners` [`number`]
244
245Default: `(number of CPU Cores)`
246Command line: `--maxConcurrentTestRunners 3`
247Config file: `maxConcurrentTestRunners: 3`
248
249Specifies the maximum number of concurrent test runners to spawn.
250Mutation testing is time consuming. By default, Stryker tries to make the most of your CPU, by spawning as many test runners as you have CPU cores.
251This setting allows you to override this default behavior.
252
253Reasons you might want to lower this setting:
254
255* Your test runner starts a browser (another CPU-intensive process)
256* You're running on a shared server and/or
257* Your hard disk cannot handle the I/O of all test runners
258
259<a name="mutate"></a>
260### `mutate` [`string[]`]
261
262Default: `['{src,lib}/**/*.js?(x)', '!{src,lib}/**/__tests__/**/*.js?(x)', '!{src,lib}/**/?(*.)+(spec|test).js?(x)', '!{src,lib}/**/*+(Spec|Test).js?(x)']`
263Command line: `[--mutate|-m] src/**/*.js,a.js`
264Config file: `mutate: ['src/**/*.js', 'a.js']`
265
266With `mutate` you configure the subset of files to use for mutation testing.
267Generally speaking, these should be your own source files.
268This is optional, as you can choose to not mutate any files at all and perform a dry-run (running only your tests without mutating).
269
270<a name="mutator"></a>
271### `mutator` [`MutatorDescriptor`]
272
273Default: `{}`
274Command line: *none*
275Config file: ``mutator: { plugins: ['classProperties', 'optionalChaining'], excludedMutations: ['BooleanSubstitution', 'StringLiteral'] }`
276
277* `plugins`: allows you to override the default [babel plugins](https://babeljs.io/docs/en/plugins) to use for JavaScript files.
278By default, Stryker uses [a default list of babel plugins to parse your JS file](https://github.com/stryker-mutator/stryker/blob/master/packages/instrumenter/src/parsers/js-parser.ts#L8-L32). It also loads any plugins or presets you might have configured yourself with `.babelrc` or `babel.config.js` files.
279In the rare situation where the plugins Stryker loads conflict with your own local plugins (for example, when using the decorators and decorators-legacy plugins together), you can override the `plugins` here to `[]`.
280* `excludedMutations`: allow you to specify a [list of mutator names](https://github.com/stryker-mutator/stryker-handbook/blob/master/mutator-types.md#supported-mutators) to be excluded (`ignored`) from the test run.
281
282_Note: prior to Stryker version 4, the mutator also needed a `name` (or be defined as `string`). This is removed in version 4. Stryker now supports mutating of JavaScript and friend files out of the box, without the need of a mutator plugin._
283
284<a name="plugins"></a>
285### `plugins` [`string[]`]
286
287Default: `['@stryker-mutator/*']`
288Command line: `--plugins @stryker-mutator/jasmine-framework,@stryker-mutator/karma-runner`
289Config file: `plugins: ['@stryker-mutator/jasmine-framework', '@stryker-mutator/karma-runner']`
290
291
292With `plugins`, you can add additional Node modules for Stryker to load (or `require`).
293By default, all `node_modules` starting with `@stryker-mutator/*` will be loaded, so you would normally not need to specify this option.
294These modules should be installed right next to stryker. For a current list of plugins,
295you can consult [npm](https://www.npmjs.com/search?q=stryker-plugin) or
296[stryker-mutator.io](https://stryker-mutator.io).
297
298<a name="reporters"></a>
299### `reporters` [`string[]`]
300
301Default: `['clear-text', 'progress', 'html']`
302Command line: `--reporters clear-text,progress,dots,dashboard,html`
303Config file: `reporters: ['clear-text', 'progress', 'dots', 'dashboard', 'html']`
304
305With `reporters`, you can set the reporters for stryker to use.
306These reporters can be used out of the box: `html`, `progress`, `clear-text`, `dots`, `dashboard` and `event-recorder`.
307By default, `clear-text`, `progress`, `html` are active if no reporters are configured.
308You can load additional plugins to get more reporters. See [stryker-mutator.io](https://stryker-mutator.io)
309for an up-to-date list of supported reporter plugins and a description on each reporter.
310
311The `html` reporter allows you to specify an output folder. This defaults to `reports/mutation/html`. The config for your config file is: `htmlReporter: { baseDir: 'mypath/reports/stryker' }`
312
313The `clear-text` reporter supports three additional config options:
314* `allowColor` to use cyan and yellow in printing source file names and positions. This defaults to `true`, so specify as `clearTextReporter: { allowColor: false },` to disable if you must.
315* `logTests` to log the names of unit tests that were run to allow mutants. By default, only the first three are logged. The config for your config file is: `clearTextReporter: { logTests: true },`
316* `maxTestsToLog` to show more tests that were executed to kill a mutant when `logTests` is true. The config for your config file is: `clearTextReporter: { logTests: true, maxTestsToLog: 7 },`
317
318The `dashboard` reporter sends a report to https://dashboard.stryker-mutator.io, enabling you to add a mutation score badge to your readme, as well as hosting your html report on the dashboard. It uses the [dashboard.*](#dashboard) configuration options. See [the Stryker handbook](https://github.com/stryker-mutator/stryker-handbook/blob/master/dashboard.md) for more info.
319
320<a name="sandbox.fileHeaders"></a>
321### `sandbox.fileHeaders` [`object`]
322
323Default: `{ "**/*+(.js|.ts|.cjs|.mjs)?(x)": "/* eslint-disable */\n// @ts-nocheck\n" }`
324Command line: *none*
325Config file: `sandbox: { fileHeaders: {} }`
326
327Configure additional headers to be added to files inside your sandbox. These headers will be added after Stryker has instrumented your code with mutants, but before a test runner or build command is executed. This is be used to ignore typescript compile errors and eslint warnings that might have been added in the process of instrumenting your code.
328
329The key here is a [glob expression](https://globster.xyz/), where the value points to the header to be used for matching files.
330
331*Note: The default setting should work for most use cases, only change this if you know what you are doing.*
332
333<a name="sandbox.stripComments"></a>
334### `sandbox.stripComments` [`false` | `string`]
335
336Default: `"**/*+(.js|.ts|.cjs|.mjs)?(x)"`
337Command line: *none*
338Config file: `sandbox: { stripComments: "" }`
339
340Configure files to be stripped of comments (either single line with `//` or multi line with `/**/`. These comments will be stripped after Stryker has instrumented your code with mutants, but before a test runner or build command is executed. This is used to remove any lingering `// @ts-check` or `// @ts-expect-error` comments that interfere with typescript compilation. The default setting allows comments to be stripped from all JavaScript and friend files in your sandbox, you can specify a different [glob expression](https://globster.xyz/) or set it to `false` to completely disable this behavior.
341
342*Note: The default setting should work for most use cases, only change this if you know what you are doing.*
343
344<a name="symlinkNodeModules"></a>
345### `symlinkNodeModules` [`boolean`]
346
347Default: `true`
348Command line: *none*
349Config file: `symlinkNodeModules: true`
350
351The `symlinkNodeModules` value indicates whether Stryker should create a [symbolic link](https://nodejs.org/api/fs.html#fs_fs_symlink_target_path_type_callback)
352to your current node_modules directory in the sandbox directories. This makes running your tests by Stryker behave
353more like your would run the tests yourself in your project directory.
354Only disable this setting if you really know what you are doing.
355
356For example, [Jest](https://jestjs.io/) expects any plugins to be located at "./node_modules/..."
357in the Sandbox directory. Another example can be running [karma](http://karma-runner.github.io/) tests where
358you specify files from the 'node_modules/angular/...'. Without symlinking the
359node_modules directory this would not be possible.
360
361Stryker will look for the node_modules directory to use in the current basePath (or current working directory) and
362its parent directories.
363
364<a name="tempDirName"></a>
365### `tempDirName` [`string`]
366
367Default: `'.stryker-tmp'`
368Command line: `--tempDirName .stryker-tmp`
369Config file: `tempDirName: '.stryker-tmp'`
370
371Choose a different temp dir that Stryker uses for mutation testing. This directory will contain copies of your source code during a mutation test run.
372It will be created if it not exists and is **entirely deleted** after a successful run, so change this with caution.
373
374It is advised to use a directory inside the directory that holds your repository. This way `node_modules` are resolved as expected. Be sure to
375not check-in your chosen temp directory in your `.gitignore` file.
376
377<a name="testFramework"></a>
378
379_Note: Use of "testFramework" is no longer needed. You can remove it from your configuration. Your test runner plugin now handles its own test framework integration_
380
381<a name="testRunner"></a>
382### `testRunner` [`string`]
383
384Default: `'command'`
385Command line: `--testRunner karma`
386Config file: `testRunner: 'karma'`
387
388With `testRunner` you specify the test runner that Stryker uses to run your tests. The default value is `command`. The command runner runs a configurable bash/cmd command and bases the result on the exit code of that program (0 for success, otherwise failed). You can configure this command via the config file using the `commandRunner: { command: 'npm run mocha' }`. It uses `npm test` as the command by default.
389
390The command test runner can be made to work in any use case, but comes with a performance
391penalty, as Stryker cannot do any optimizations and just runs all tests for all mutants.
392If possible, you should try to use one of the test runner plugins that hook into your test runner of choice.
393For example: install and use the `stryker-karma-runner` to use `karma` as a test runner.
394See the [list of plugins](https://stryker-mutator.io/plugins.html) for an up-to-date list of supported test runners and plugins.
395
396<a name="thresholds"></a>
397### `thresholds` [`object`]
398
399Default: `{ high: 80, low: 60, break: null }`
400Command line: *none*
401Config file: `thresholds: { high: 80, low: 60, break: null }`
402
403Description
404Specify the thresholds for mutation score.
405
406* `mutation score >= high`: Awesome! Reporters should color this green and happy.
407* `high > mutation score >= low`: Warning! Reporters should color this orange/yellow. Watch yourself!
408* `mutation score < low`: Danger! Reporters should color this in red. You're in danger!
409* `mutation score < break`: Error! Stryker will exit with exit code 1, indicating a build failure. No consequence for reporters, though.
410
411It is not allowed to only supply one value of the values (it's all or nothing). However, `high` and `low` values can be the same, making sure colors are either red or green. Set `break` to `null` (default) to never let your build fail.
412
413<a name="timeoutFactor"></a>
414### `timeoutFactor` [`number`]
415
416Default: `1.5`
417Command line: `--timeoutFactor 1.5`
418Config file: `timeoutFactor: 1.5`
419
420See [Timeout in milliseconds](#timeoutMS).
421
422<a name="timeoutMS"></a>
423### `timeoutMS` [`number`]
424
425Default: `5000`
426Command line: `--timeoutMS 5000`
427Config file: `timeoutMS: 5000`
428
429
430When Stryker is mutating code, it cannot determine indefinitely whether a code mutation results in an infinite loop (see [Halting problem](https://en.wikipedia.org/wiki/Halting_problem)).
431In order to battle infinite loops, a test run gets killed after a certain period of time. This period is configurable with two settings: `timeoutMS` and `timeoutFactor`.
432To calculate the actual timeout in milliseconds the, following formula is used:
433
434```
435timeoutForTestRunMs = netTimeMs * timeoutFactor + timeoutMS + overheadMs
436```
437
438Both `netTimeMs` and `overheadMs` are calculated during the initial test run. They are logged on `info` level. For example when `overheadMs` is 92 and `netTimeMs` is 5: `Initial test run succeeded. Ran 6 tests in 4 seconds (net 5 ms, overhead 92 ms).`
439
440With `timeoutFactor` you can configure the allowed deviation relative to the time of a normal test run. Tweak this if you notice that mutants are prone to creating slower code, but not infinite loops.
441`timeoutMS` lets you configure an absolute deviation. Use it, if you run Stryker on a busy machine and you need to wait longer to make sure that the code indeed entered an infinite loop.
442
443<a name="transpilers"></a>
444
445_Note: Support for "transpilers" plugins is removed since Stryker 4. You can now configure your own [buildCommand](#buildCommand)_