UNPKG

21.5 kBMarkdownView Raw
1[![Build Status](https://github.com/stryker-mutator/stryker/workflows/CI/badge.svg)](https://github.com/stryker-mutator/stryker/actions?query=workflow%3ACI+branch%3Amaster)
2[![NPM](https://img.shields.io/npm/dm/@stryker-mutator/core.svg)](https://www.npmjs.com/package/@stryker-mutator/core)
3[![Node version](https://img.shields.io/node/v/@stryker-mutator/core.svg)](https://img.shields.io/node/v/@stryker-mutator/core.svg)
4[![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)
5
6![Stryker](https://github.com/stryker-mutator/stryker/raw/master/stryker-80x80.png)
7
8# Stryker
9*Professor X: For someone who hates mutants... you certainly keep some strange company.*
10*William Stryker: Oh, they serve their purpose... as long as they can be controlled.*
11
12## Introduction
13For an introduction to mutation testing and Stryker's features, see [stryker-mutator.io](https://stryker-mutator.io/).
14
15## Getting started
16
17Please follow the [quickstart on the website](https://stryker-mutator.io/stryker/quickstart).
18
19For small js projects, you can try the following command:
20
21```
22npm install --save-dev @stryker-mutator/core
23# Only for small projects:
24npx stryker run
25```
26
27It will run stryker with default values:
28
29* Uses `npm test` as your test command
30* Searches for files to mutate in the `lib` and `src` directories
31
32## Usage
33
34```sh
35$ npx stryker <command> [options] [stryker.conf.js]
36```
37
38The main `command` for Stryker is `run`, which kicks off mutation testing.
39
40Although 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.
41
42Before 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.
43
44The following is an example `stryker.conf.js` file. It specifies running mocha tests with the mocha test runner.
45
46```javascript
47module.exports = function(config){
48 config.set({
49 mutate: [
50 'src/**/*.js',
51 '!src/index.js'
52 ],
53 testFramework: 'mocha',
54 testRunner: 'mocha',
55 reporters: ['progress', 'clear-text', 'html'],
56 coverageAnalysis: 'perTest'
57 });
58}
59```
60
61As 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.
62
63Make sure you *at least* specify the `testRunner` options when mixing the config file and/or command line options.
64
65## Command-line interface
66Stryker 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.
67
68You can install the Stryker-CLI using:
69
70```bash
71$ npm install -g stryker-cli
72```
73
74The 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.
75
76## Supported mutators
77
78See our website for the [list of currently supported mutators](https://stryker-mutator.io/mutators.html).
79
80## Configuration
81
82All configuration options can either be set via the command line or via the `stryker.conf.js` config file.
83
84`files` and `mutate` both support globbing expressions using [node glob](https://github.com/isaacs/node-glob).
85This is the same globbing format you might know from [Grunt](https://github.com/gruntjs/grunt) or [Karma](https://github.com/karma-runner/karma).
86
87You can *ignore* files by adding an exclamation mark (`!`) at the start of an expression.
88
89### Available Options
90* [allowConsoleColors](#allowConsoleColors)
91* [coverageAnalysis](#coverageAnalysis)
92* [fileLogLevel](#fileLogLevel)
93* [files](#files)
94* [logLevel](#logLevel)
95* [maxConcurrentTestRunners](#maxConcurrentTestRunners)
96* [mutate](#mutate)
97* [mutator](#mutator)
98* [plugins](#plugins)
99* [reporters](#reporters)
100* [symlinkNodeModules](#symlinkNodeModules)
101* [tempDirName](#tempDirName)
102* [testFramework](#testFramework)
103* [testRunner](#testRunner)
104* [thresholds](#thresholds)
105* [timeoutFactor](#timeoutFactor)
106* [timeoutMS](#timeoutMS)
107* [transpilers](#transpilers)
108
109<a name="allowConsoleColors"></a>
110### `allowConsoleColors` [`boolean`]
111
112Default: `true`
113Command line: `--allowConsoleColors true`
114Config file: `allowConsoleColors: true`
115
116The `allowConsoleColors` value indicates whether Stryker should use colors in console.
117
118<a name="coverageAnalysis"></a>
119### `coverageAnalysis` [`string`]
120
121Default: `off`
122Command line: `--coverageAnalysis perTest`
123Config file: `coverageAnalysis: 'perTest'`
124
125With `coverageAnalysis` you specify which coverage analysis strategy you want to use.
126
127Stryker can analyse code coverage results. This can potentially speed up mutation testing a lot, as only the tests covering a
128particular mutation are tested for each mutant.
129This does *not* influence the resulting mutation testing score. It only improves performance, so we enable it by default.
130
131The possible values are:
132* **off**: Stryker will not determine the code covered by tests during the initial test run phase. All tests will be executed for each mutant
133during the mutation testing phase.
134
135* **all**: Stryker will determine the code covered by all tests during the initial test run phase. Only mutants actually covered by your
136test 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.
137Currently, only the `stryker-mocha-runner` and the `stryker-karma-runner` do this.
138
139* **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
140test suite are tested during the mutation testing phase.
141Only 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.
142In 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
143 before and after each test, as well as test filtering.
144 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
145 (`Mocha` is not yet supported).
146
147<a name="fileLogLevel"></a>
148### `fileLogLevel` [`string`]
149
150 Default: `off`
151 Command line: `--fileLogLevel info`
152 Config file: `fileLogLevel: 'info'`
153
154 Set the log level that Stryker uses to write to the "stryker.log" file. Possible values: `off`, `fatal`, `error`, `warn`, `info`, `debug` and `trace`
155
156<a name="files"></a>
157### `files` [`string[]`]
158
159Default: result of `git ls-files --others --exclude-standard --cached --exclude .stryker-tmp`
160Command line: `[--files|-f] src/**/*.js,a.js,test/**/*.js`
161Config file: `files: ['src/**/*.js', '!src/**/index.js', 'test/**/*.js']`
162
163With `files`, you can choose which files should be included in your test runner sandbox.
164This is normally not needed as it defaults to all files not ignored by git.
165Try it out yourself with this command: `git ls-files --others --exclude-standard --cached --exclude .stryker-tmp`.
166
167If you do need to override `files` (for example: when your project does not live in a git repository),
168you can override the files here.
169
170When using the command line, the list can only contain a comma separated list of globbing expressions.
171When using the config file you can provide an array with `string`s
172
173You can *ignore* files by adding an exclamation mark (`!`) at the start of an expression.
174
175<a name="logLevel"></a>
176### `logLevel` [`string`]
177
178Default: `info`
179Command line: `--logLevel info`
180Config file: `logLevel: 'info'`
181
182
183 Set the log level that Stryker uses to write to the console. Possible values: `off`, `fatal`, `error`, `warn`, `info`, `debug` and `trace`
184
185 *Note*: Test runners are run as child processes of the Stryker Node process. All output (stdout) of the `testRunner` is logged as `trace`.
186 Thus, to see logging output from the test runner set the `logLevel` to `all` or `trace`.
187
188<a name="maxConcurrentTestRunners"></a>
189### `maxConcurrentTestRunners` [`number`]
190
191Default: `(number of CPU Cores)`
192Command line: `--maxConcurrentTestRunners 3`
193Config file: `maxConcurrentTestRunners: 3`
194
195Specifies the maximum number of concurrent test runners to spawn.
196Mutation 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.
197This setting allows you to override this default behavior.
198
199Reasons you might want to lower this setting:
200
201* Your test runner starts a browser (another CPU-intensive process)
202* You're running on a shared server and/or
203* Your hard disk cannot handle the I/O of all test runners
204
205<a name="mutate"></a>
206### `mutate` [`string[]`]
207
208Default: `['{src,lib}/**/*.js?(x)', '!{src,lib}/**/__tests__/**/*.js?(x)', '!{src,lib}/**/?(*.)+(spec|test).js?(x)', '!{src,lib}/**/*+(Spec|Test).js?(x)']`
209Command line: `[--mutate|-m] src/**/*.js,a.js`
210Config file: `mutate: ['src/**/*.js', 'a.js']`
211
212With `mutate` you configure the subset of files to use for mutation testing.
213Generally speaking, these should be your own source files.
214This is optional, as you can choose to not mutate any files at all and perform a dry-run (running only your tests without mutating).
215
216<a name="mutator"></a>
217### `mutator` [`object` | `string`]
218Default: `javascript`
219Command line: `--mutator javascript`
220Config file: `mutator: 'javascript'` or `mutator: { name: 'javascript', plugins: ['classProperties', 'optionalChaining'], excludedMutations: ['BooleanSubstitution', 'StringLiteral'] }`
221
222With `mutator` you configure which mutator plugin you want to use, and optionally, which mutation types to exclude from the test run.
223The 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.
224The 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.
225
226When using the command line, only the mutator name as a string may be provided.
227When using the config file, you can provide either a string representing the mutator name, or a `MutatorDescriptor` object, like so:
228
229* `MutatorDescriptor` object: `{ name: 'name', plugins: ['classProperties', 'optionalChaining'], excludedMutations: ['mutationType1', 'mutationType2', ...] }`:
230 * The `name` property is mandatory and contains the name of the mutator plugin to use.
231 * 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.
232 * The `excludedMutations` property is mandatory and contains the types of mutations to exclude from the test run.
233
234<a name="plugins"></a>
235### `plugins` [`string[]`]
236
237Default: `['@stryker-mutator/*']`
238Command line: `--plugins stryker-html-reporter,stryker-karma-runner`
239Config file: `plugins: ['stryker-html-reporter', 'stryker-karma-runner']`
240
241
242With `plugins`, you can add additional Node modules for Stryker to load (or `require`).
243By default, all `node_modules` starting with `@stryker-mutator/*` will be loaded, so you would normally not need to specify this option.
244These modules should be installed right next to stryker. For a current list of plugins,
245you can consult [npm](https://www.npmjs.com/search?q=%40stryker-plugin) or
246[stryker-mutator.io](https://stryker-mutator.io).
247
248<a name="reporters"></a>
249### `reporters` [`string[]`]
250
251Default: `['clear-text', 'progress']`
252Command line: `--reporters clear-text,progress,dots,dashboard`
253Config file: `reporters: ['clear-text', 'progress', 'dots', 'dashboard']`
254
255With `reporters`, you can set the reporters for stryker to use.
256These reporters can be used out of the box: `clear-text`, `progress`, `dots`, `dashboard` and `event-recorder`.
257By default, `clear-text` and `progress` are active if no reporters are configured.
258You can load additional plugins to get more reporters. See [stryker-mutator.io](https://stryker-mutator.io)
259for an up-to-date list of supported reporter plugins and a description on each reporter.
260
261The `clear-text` reporter supports three additional config options:
262* `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.
263* `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 },`
264* `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 },`
265
266The `dashboard` reporter is a special kind of reporter. It sends a report to https://dashboard.stryker-mutator.io, enabling you to add a fancy mutation score badge to your readme! To make sure no unwanted results are sent to the dashboards, it will only send the report if it is run from a build server. The reporter currently detects [Travis](https://travis-ci.org/) and [CircleCI](https://circleci.com/). Please open an [issue](https://github.com/stryker-mutator/stryker/issues/new) if your build server is missing. On all these environments, it will ignore builds of pull requests. Apart from build server specific environment variables, the reporter uses one environment variable:
267
268| Environment variable | Description | Example value |
269| ------------- | ------------- | ----- |
270| STRYKER\_DASHBOARD\_API\_KEY | Your API key (generated at https://dashboard.stryker-mutator.io) | `52248872-2edc-4102-a43a-bcfca7a9ca99` |
271
272You will need to pass the `STRYKER_DASHBOARD_API_KEY` environment variable yourself. You can create one for your repository by logging in on [the Stryker dashboard](https://dashboard.stryker-mutator.io). We strongly recommend you use encrypted environment variables:
273* [Travis documentation](https://docs.travis-ci.com/user/environment-variables/#Encrypting-environment-variables)
274* [CircleCI documentation](https://circleci.com/security/#secrets_section)
275
276<a name="symlinkNodeModules"></a>
277### `symlinkNodeModules` [`boolean`]
278
279Default: `true`
280Command line: *none*
281Config file: `symlinkNodeModules: true`
282
283
284The `symlinkNodeModules` value indicates whether Stryker should create a [symbolic link](https://nodejs.org/api/fs.html#fs_fs_symlink_target_path_type_callback)
285to your current node_modules directory in the sandbox directories. This makes running your tests by Stryker behave
286more like your would run the tests yourself in your project directory.
287Only disable this setting if you really know what you are doing.
288
289For example, [Jest](https://facebook.github.io/) expects any plugins to be located at "./node_modules/..."
290in the Sandbox directory. Another example can be running [karma](http://karma-runner.github.io/) tests where
291you specify files from the 'node_modules/angular/...'. Without symlinking the
292node_modules directory this would not be possible.
293
294Stryker will look for the node_modules directory to use in the current basePath (or current working directory) and
295its parent directories.
296
297<a name="tempDirName"></a>
298### `tempDirName` [`string`]
299
300Default: `'.stryker-tmp'`
301Command line: `--tempDirName .stryker-tmp`
302Config file: `tempDirName: '.stryker-tmp'`
303
304Choose a different temp dir that Stryker uses for mutation testing. This directory will contain copies of your source code during a mutation test run.
305It will be created if it not exists and is **entirely deleted** after a successful run, so change this with caution.
306
307It is advised to use a directory inside the directory that holds your repository. This way `node_modules` are resolved as expected. Be sure to
308not check-in your chosen temp directory in your `.gitignore` file.
309
310<a name="testFramework"></a>
311### `testFramework` [`string`]
312
313Default: *none*
314Command line: `--testFramework jasmine`
315Config file: `testFramework: 'jasmine'`
316
317Configure which test framework you are using.
318This option is not mandatory, as Stryker is test framework agnostic (it doesn't care what framework you use),
319However, 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.
320
321Make sure the plugin is installed for your chosen test framework. E.g. install `stryker-mocha-framework` to use `'mocha'` as a test framework.
322
323<a name="testRunner"></a>
324### `testRunner` [`string`]
325
326Default: `'command'`
327Command line: `--testRunner karma`
328Config file: `testRunner: 'karma'`
329
330With `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.
331
332The command test runner can be made to work in any use case, but comes with a performance
333penalty, as Stryker cannot do any optimizations and just runs all tests for all mutants.
334If possible, you should try to use one of the test runner plugins that hook into your test runner of choice.
335For example: install and use the `stryker-karma-runner` to use `karma` as a test runner.
336See the [list of plugins](https://stryker-mutator.io/plugins.html) for an up-to-date list of supported test runners and plugins.
337
338<a name="thresholds"></a>
339### `thresholds` [`object`]
340
341Default: `{ high: 80, low: 60, break: null }`
342Command line: *none*
343Config file: `thresholds: { high: 80, low: 60, break: null }`
344
345Description
346Specify the thresholds for mutation score.
347
348* `mutation score >= high`: Awesome! Reporters should color this green and happy.
349* `high > mutation score >= low`: Warning! Reporters should color this orange/yellow. Watch yourself!
350* `mutation score < low`: Danger! Reporters should color this in red. You're in danger!
351* `mutation score < break`: Error! Stryker will exit with exit code 1, indicating a build failure. No consequence for reporters, though.
352
353It 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.
354
355<a name="timeoutFactor"></a>
356### `timeoutFactor` [`number`]
357
358Default: `1.5`
359Command line: `--timeoutFactor 1.5`
360Config file: `timeoutFactor: 1.5`
361
362See [Timeout in milliseconds](#Timeout-in-milliseconds).
363
364<a name="timeoutMS"></a>
365### `timeoutMS` [`number`]
366
367Default: `5000`
368Command line: `--timeoutMS 5000`
369Config file: `timeoutMS: 5000`
370
371
372When 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)).
373In 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`.
374To calculate the actual timeout in milliseconds the, following formula is used:
375
376```
377timeoutForTestRunMs = netTimeMs * timeoutFactor + timeoutMS + overheadMs
378```
379
380Both `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).`
381
382With `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.
383`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.
384
385<a name="transpilers"></a>
386### `transpilers` [`string[]`]
387
388Default: `[]`
389
390With `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.