UNPKG

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