UNPKG

21.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[![Gitter](https://badges.gitter.im/stryker-mutator/stryker.svg)](https://gitter.im/stryker-mutator/stryker?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
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] [stryker.conf.js]
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` 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 `stryker.conf.js` 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.js` file. It specifies running mocha tests with the mocha test runner.
46
47```javascript
48module.exports = function(config){
49 config.set({
50 mutate: [
51 'src/**/*.js',
52 '!src/index.js'
53 ],
54 testFramework: 'mocha',
55 testRunner: 'mocha',
56 reporters: ['progress', 'clear-text', 'html'],
57 coverageAnalysis: 'perTest'
58 });
59}
60```
61
62As you can see, the config file is *not* a simple JSON file. It should be a node module. You might recognize this way of working from the karma test runner.
63
64Make sure you *at least* specify the `testRunner` options when mixing the config file and/or command line options.
65
66## Command-line interface
67Stryker 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.
68
69You can install the Stryker-CLI using:
70
71```bash
72$ npm install -g stryker-cli
73```
74
75The 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.
76
77## Supported mutators
78
79See our website for the [list of currently supported mutators](https://stryker-mutator.io/mutators.html).
80
81## Configuration
82
83All configuration options can either be set via the command line or via the `stryker.conf.js` config file.
84
85`files` and `mutate` both support globbing expressions using [node glob](https://github.com/isaacs/node-glob).
86This is the same globbing format you might know from [Grunt](https://github.com/gruntjs/grunt) or [Karma](https://github.com/karma-runner/karma).
87
88You can *ignore* files by adding an exclamation mark (`!`) at the start of an expression.
89
90### Available Options
91* [allowConsoleColors](#allowConsoleColors)
92* [coverageAnalysis](#coverageAnalysis)
93* [dashboard.*](#dashboard)
94* [fileLogLevel](#fileLogLevel)
95* [files](#files)
96* [logLevel](#logLevel)
97* [maxConcurrentTestRunners](#maxConcurrentTestRunners)
98* [mutate](#mutate)
99* [mutator](#mutator)
100* [plugins](#plugins)
101* [reporters](#reporters)
102* [symlinkNodeModules](#symlinkNodeModules)
103* [tempDirName](#tempDirName)
104* [testFramework](#testFramework)
105* [testRunner](#testRunner)
106* [thresholds](#thresholds)
107* [timeoutFactor](#timeoutFactor)
108* [timeoutMS](#timeoutMS)
109* [transpilers](#transpilers)
110
111<a name="allowConsoleColors"></a>
112### `allowConsoleColors` [`boolean`]
113
114Default: `true`
115Command line: `--allowConsoleColors true`
116Config file: `allowConsoleColors: true`
117
118The `allowConsoleColors` value indicates whether Stryker should use colors in console.
119
120<a name="coverageAnalysis"></a>
121### `coverageAnalysis` [`string`]
122
123Default: `off`
124Command line: `--coverageAnalysis perTest`
125Config file: `coverageAnalysis: 'perTest'`
126
127With `coverageAnalysis` you specify which coverage analysis strategy you want to use.
128
129Stryker can analyse code coverage results. This can potentially speed up mutation testing a lot, as only the tests covering a
130particular mutation are tested for each mutant.
131This does *not* influence the resulting mutation testing score. It only improves performance, so we enable it by default.
132
133The possible values are:
134* **off**: Stryker will not determine the code covered by tests during the initial test run phase. All tests will be executed for each mutant
135during the mutation testing phase.
136
137* **all**: Stryker will determine the code covered by all tests during the initial test run phase. Only mutants actually covered by your
138test 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.
139Currently, only the `stryker-mocha-runner` and the `stryker-karma-runner` do this.
140
141* **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
142test suite are tested during the mutation testing phase.
143Only 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.
144In addition to requiring your test runner to be able to report the code coverage back to Stryker, your chosen `testFramework` also needs to support running code
145 before and after each test, as well as test filtering.
146 Currently, `stryker-mocha-runner` as well as `stryker-karma-runner` support this. However, `stryker-karma-runner` support is limited to using it with `Jasmine` as the test framework
147 (`Mocha` is not yet supported).
148
149<a name="dashboard"></a>
150### `dashboard` [`DashboardOptions`]
151
152Default: `{ baseUrl: 'https://dashboard.stryker-mutator.io/api/reports', reportType: 'mutationScore' }`
153Command 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`
154Config 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' }`
155
156Settings for the `dashboard` [reporter](#reporters). See the [stryker handbook for more info](https://github.com/stryker-mutator/stryker-handbook/blob/master/dashboard.md)
157
158<a name="fileLogLevel"></a>
159### `fileLogLevel` [`string`]
160
161 Default: `off`
162 Command line: `--fileLogLevel info`
163 Config file: `fileLogLevel: 'info'`
164
165 Set the log level that Stryker uses to write to the "stryker.log" file. Possible values: `off`, `fatal`, `error`, `warn`, `info`, `debug` and `trace`
166
167<a name="files"></a>
168### `files` [`string[]`]
169
170Default: result of `git ls-files --others --exclude-standard --cached --exclude .stryker-tmp`
171Command line: `[--files|-f] src/**/*.js,a.js,test/**/*.js`
172Config file: `files: ['src/**/*.js', '!src/**/index.js', 'test/**/*.js']`
173
174With `files`, you can choose which files should be included in your test runner sandbox.
175This is normally not needed as it defaults to all files not ignored by git.
176Try it out yourself with this command: `git ls-files --others --exclude-standard --cached --exclude .stryker-tmp`.
177
178If you do need to override `files` (for example: when your project does not live in a git repository),
179you can override the files here.
180
181When using the command line, the list can only contain a comma separated list of globbing expressions.
182When using the config file you can provide an array with `string`s
183
184You can *ignore* files by adding an exclamation mark (`!`) at the start of an expression.
185
186<a name="logLevel"></a>
187### `logLevel` [`string`]
188
189Default: `info`
190Command line: `--logLevel info`
191Config file: `logLevel: 'info'`
192
193
194 Set the log level that Stryker uses to write to the console. Possible values: `off`, `fatal`, `error`, `warn`, `info`, `debug` and `trace`
195
196 *Note*: Test runners are run as child processes of the Stryker Node process. All output (stdout) of the `testRunner` is logged as `trace`.
197 Thus, to see logging output from the test runner set the `logLevel` to `all` or `trace`.
198
199<a name="maxConcurrentTestRunners"></a>
200### `maxConcurrentTestRunners` [`number`]
201
202Default: `(number of CPU Cores)`
203Command line: `--maxConcurrentTestRunners 3`
204Config file: `maxConcurrentTestRunners: 3`
205
206Specifies the maximum number of concurrent test runners to spawn.
207Mutation 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.
208This setting allows you to override this default behavior.
209
210Reasons you might want to lower this setting:
211
212* Your test runner starts a browser (another CPU-intensive process)
213* You're running on a shared server and/or
214* Your hard disk cannot handle the I/O of all test runners
215
216<a name="mutate"></a>
217### `mutate` [`string[]`]
218
219Default: `['{src,lib}/**/*.js?(x)', '!{src,lib}/**/__tests__/**/*.js?(x)', '!{src,lib}/**/?(*.)+(spec|test).js?(x)', '!{src,lib}/**/*+(Spec|Test).js?(x)']`
220Command line: `[--mutate|-m] src/**/*.js,a.js`
221Config file: `mutate: ['src/**/*.js', 'a.js']`
222
223With `mutate` you configure the subset of files to use for mutation testing.
224Generally speaking, these should be your own source files.
225This is optional, as you can choose to not mutate any files at all and perform a dry-run (running only your tests without mutating).
226
227<a name="mutator"></a>
228### `mutator` [`object` | `string`]
229Default: `javascript`
230Command line: `--mutator javascript`
231Config file: `mutator: 'javascript'` or `mutator: { name: 'javascript', plugins: ['classProperties', 'optionalChaining'], excludedMutations: ['BooleanSubstitution', 'StringLiteral'] }`
232
233With `mutator` you configure which mutator plugin you want to use, and optionally, which mutation types to exclude from the test run.
234The mutator plugin name defaults to `javascript` if not specified. Note: this requires you to have the `@stryker-mutator/javascript-mutator` plugin installed. The list of excluded mutation types defaults to an empty array, meaning all mutation types will be included in the test.
235The full list of mutation types varies slightly between mutators (for example, the `javascript` mutator will not use the same mutation types as the `typescript` mutator). Mutation type names are case-sensitive, and can be found either in the source code or in a generated Stryker report.
236
237When using the command line, only the mutator name as a string may be provided.
238When using the config file, you can provide either a string representing the mutator name, or a `MutatorDescriptor` object, like so:
239
240* `MutatorDescriptor` object: `{ name: 'name', plugins: ['classProperties', 'optionalChaining'], excludedMutations: ['mutationType1', 'mutationType2', ...] }`:
241 * The `name` property is mandatory and contains the name of the mutator plugin to use.
242 * The `plugins` property is optional and allows you to specify syntax plugins. Please see the README of your mutator to see which plugins are supported.
243 * The `excludedMutations` property is mandatory and contains the types of mutations to exclude from the test run.
244
245<a name="plugins"></a>
246### `plugins` [`string[]`]
247
248Default: `['@stryker-mutator/*']`
249Command line: `--plugins stryker-html-reporter,stryker-karma-runner`
250Config file: `plugins: ['stryker-html-reporter', 'stryker-karma-runner']`
251
252
253With `plugins`, you can add additional Node modules for Stryker to load (or `require`).
254By default, all `node_modules` starting with `@stryker-mutator/*` will be loaded, so you would normally not need to specify this option.
255These modules should be installed right next to stryker. For a current list of plugins,
256you can consult [npm](https://www.npmjs.com/search?q=%40stryker-plugin) or
257[stryker-mutator.io](https://stryker-mutator.io).
258
259<a name="reporters"></a>
260### `reporters` [`string[]`]
261
262Default: `['clear-text', 'progress']`
263Command line: `--reporters clear-text,progress,dots,dashboard,html`
264Config file: `reporters: ['clear-text', 'progress', 'dots', 'dashboard', 'html']`
265
266With `reporters`, you can set the reporters for stryker to use.
267These reporters can be used out of the box: `clear-text`, `progress`, `dots`, `dashboard` and `event-recorder`.
268The `html` reporter can be installed as a plugin, see [the html reporter's readme](https://github.com/stryker-mutator/stryker/tree/master/packages/html-reporter#readme).
269By default, `clear-text` and `progress` are active if no reporters are configured.
270You can load additional plugins to get more reporters. See [stryker-mutator.io](https://stryker-mutator.io)
271for an up-to-date list of supported reporter plugins and a description on each reporter.
272
273The `clear-text` reporter supports three additional config options:
274* `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.
275* `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 },`
276* `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 },`
277
278The `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.
279
280<a name="symlinkNodeModules"></a>
281### `symlinkNodeModules` [`boolean`]
282
283Default: `true`
284Command line: *none*
285Config file: `symlinkNodeModules: true`
286
287The `symlinkNodeModules` value indicates whether Stryker should create a [symbolic link](https://nodejs.org/api/fs.html#fs_fs_symlink_target_path_type_callback)
288to your current node_modules directory in the sandbox directories. This makes running your tests by Stryker behave
289more like your would run the tests yourself in your project directory.
290Only disable this setting if you really know what you are doing.
291
292For example, [Jest](https://jestjs.io/) expects any plugins to be located at "./node_modules/..."
293in the Sandbox directory. Another example can be running [karma](http://karma-runner.github.io/) tests where
294you specify files from the 'node_modules/angular/...'. Without symlinking the
295node_modules directory this would not be possible.
296
297Stryker will look for the node_modules directory to use in the current basePath (or current working directory) and
298its parent directories.
299
300<a name="tempDirName"></a>
301### `tempDirName` [`string`]
302
303Default: `'.stryker-tmp'`
304Command line: `--tempDirName .stryker-tmp`
305Config file: `tempDirName: '.stryker-tmp'`
306
307Choose a different temp dir that Stryker uses for mutation testing. This directory will contain copies of your source code during a mutation test run.
308It will be created if it not exists and is **entirely deleted** after a successful run, so change this with caution.
309
310It is advised to use a directory inside the directory that holds your repository. This way `node_modules` are resolved as expected. Be sure to
311not check-in your chosen temp directory in your `.gitignore` file.
312
313<a name="testFramework"></a>
314### `testFramework` [`string`]
315
316Default: *none*
317Command line: `--testFramework jasmine`
318Config file: `testFramework: 'jasmine'`
319
320Configure which test framework you are using.
321This option is not mandatory, as Stryker is test framework agnostic (it doesn't care what framework you use),
322However, it is required when `coverageAnalysis` is set to `'perTest'`, because Stryker needs to hook into the test framework in order to measure code coverage results per test and filter tests to run.
323
324Make sure the plugin is installed for your chosen test framework. E.g. install `stryker-mocha-framework` to use `'mocha'` as a test framework.
325
326<a name="testRunner"></a>
327### `testRunner` [`string`]
328
329Default: `'command'`
330Command line: `--testRunner karma`
331Config file: `testRunner: 'karma'`
332
333With `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.
334
335The command test runner can be made to work in any use case, but comes with a performance
336penalty, as Stryker cannot do any optimizations and just runs all tests for all mutants.
337If possible, you should try to use one of the test runner plugins that hook into your test runner of choice.
338For example: install and use the `stryker-karma-runner` to use `karma` as a test runner.
339See the [list of plugins](https://stryker-mutator.io/plugins.html) for an up-to-date list of supported test runners and plugins.
340
341<a name="thresholds"></a>
342### `thresholds` [`object`]
343
344Default: `{ high: 80, low: 60, break: null }`
345Command line: *none*
346Config file: `thresholds: { high: 80, low: 60, break: null }`
347
348Description
349Specify the thresholds for mutation score.
350
351* `mutation score >= high`: Awesome! Reporters should color this green and happy.
352* `high > mutation score >= low`: Warning! Reporters should color this orange/yellow. Watch yourself!
353* `mutation score < low`: Danger! Reporters should color this in red. You're in danger!
354* `mutation score < break`: Error! Stryker will exit with exit code 1, indicating a build failure. No consequence for reporters, though.
355
356It 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.
357
358<a name="timeoutFactor"></a>
359### `timeoutFactor` [`number`]
360
361Default: `1.5`
362Command line: `--timeoutFactor 1.5`
363Config file: `timeoutFactor: 1.5`
364
365See [Timeout in milliseconds](#timeoutMS).
366
367<a name="timeoutMS"></a>
368### `timeoutMS` [`number`]
369
370Default: `5000`
371Command line: `--timeoutMS 5000`
372Config file: `timeoutMS: 5000`
373
374
375When 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)).
376In 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`.
377To calculate the actual timeout in milliseconds the, following formula is used:
378
379```
380timeoutForTestRunMs = netTimeMs * timeoutFactor + timeoutMS + overheadMs
381```
382
383Both `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).`
384
385With `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.
386`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.
387
388<a name="transpilers"></a>
389### `transpilers` [`string[]`]
390
391Default: `[]`
392
393With `transpilers` you configure which transpiler plugins should transpile the code before it's executed. This is an array where the transpilers are called in the other of the array. This defaults to an empty array meaning no transpilation will be done.
394