0
# Stryker Mutator Core
1
2
The extendable JavaScript mutation testing framework core package. StrykerJS systematically introduces small code changes (mutations) to test files to verify the effectiveness of your test suite. It provides a robust plugin architecture supporting multiple test runners and comprehensive reporting.
3
4
## Package Information
5
6
- **Package Name**: @stryker-mutator/core
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @stryker-mutator/core`
10
- **License**: Apache-2.0
11
- **Node.js Version**: >= 20.0.0
12
13
## Core Imports
14
15
```typescript
16
import { Stryker, StrykerCli } from "@stryker-mutator/core";
17
```
18
19
Default import for backward compatibility:
20
21
```typescript
22
import Stryker from "@stryker-mutator/core";
23
```
24
25
Mixed import:
26
27
```typescript
28
import Stryker, { StrykerCli } from "@stryker-mutator/core";
29
```
30
31
## Basic Usage
32
33
### Programmatic Usage
34
35
```typescript
36
import { Stryker } from "@stryker-mutator/core";
37
import { PartialStrykerOptions, MutantResult } from "@stryker-mutator/api/core";
38
39
// Configure Stryker with options
40
const options: PartialStrykerOptions = {
41
testRunner: 'jest',
42
mutate: ['src/**/*.js', '!src/index.js'],
43
reporters: ['html', 'clear-text'],
44
coverageAnalysis: 'perTest'
45
};
46
47
// Create and run mutation testing
48
const stryker = new Stryker(options);
49
const results: MutantResult[] = await stryker.runMutationTest();
50
51
console.log(`Found ${results.length} mutants`);
52
```
53
54
### CLI Usage
55
56
```typescript
57
import { StrykerCli } from "@stryker-mutator/core";
58
59
// Create CLI instance with command line arguments
60
const cli = new StrykerCli(process.argv);
61
cli.run();
62
```
63
64
65
## Architecture
66
67
Stryker Core is built around several key concepts:
68
69
- **Minimal Public API**: Only 2 main exports despite extensive internal architecture
70
- **Plugin-Based Extension**: Internal components accessible via plugin system, not direct exports
71
- **CLI-First Interface**: Primary usage through command-line via StrykerCli
72
- **Configuration-Driven**: Behavior controlled through configuration rather than programmatic API
73
- **Mutation Testing Process**: Systematic introduction of code changes to validate test effectiveness
74
75
The package contains extensive internal functionality including process executors, reporters, configuration system, and DI container, but these are deliberately not exposed as public APIs.
76
77
## Capabilities
78
79
### Stryker Class
80
81
Main mutation testing orchestrator class that executes the complete mutation testing process.
82
83
```typescript { .api }
84
class Stryker {
85
/**
86
* Creates a new Stryker instance
87
* @param cliOptions - Configuration options for mutation testing
88
* @param injectorFactory - Dependency injection factory (for testing purposes)
89
*/
90
constructor(
91
cliOptions: PartialStrykerOptions,
92
injectorFactory?: Function
93
);
94
95
/**
96
* Executes the complete mutation testing process
97
* @returns Promise resolving to array of mutant test results
98
*/
99
runMutationTest(): Promise<MutantResult[]>;
100
}
101
```
102
103
**Usage Example:**
104
105
```typescript
106
import { Stryker } from "@stryker-mutator/core";
107
108
const stryker = new Stryker({
109
testRunner: 'mocha',
110
mutate: ['src/**/*.ts'],
111
reporters: ['progress', 'html'],
112
thresholds: { high: 80, low: 60, break: 50 }
113
});
114
115
const results = await stryker.runMutationTest();
116
console.log(`Mutation testing completed with ${results.length} mutants`);
117
```
118
119
### StrykerCli Class
120
121
Command-line interface implementation providing CLI access to Stryker functionality.
122
123
```typescript { .api }
124
import { Command } from 'commander';
125
126
class StrykerCli {
127
/**
128
* Creates a new StrykerCli instance
129
* @param argv - Command line arguments array
130
* @param program - Commander program instance (optional)
131
* @param runMutationTest - Mutation test runner function (optional)
132
* @param runMutationTestingServer - Mutation server runner function (optional)
133
*/
134
constructor(
135
argv: string[],
136
program?: Command,
137
runMutationTest?: (options: PartialStrykerOptions) => Promise<MutantResult[]>,
138
runMutationTestingServer?: (options: PartialStrykerOptions) => Promise<void>
139
);
140
141
/**
142
* Parses command line arguments and executes the appropriate command
143
* Supports commands: run, init, runServer
144
*/
145
run(): void;
146
}
147
```
148
149
**Usage Example:**
150
151
```typescript
152
import { StrykerCli } from "@stryker-mutator/core";
153
154
// Create CLI with process arguments
155
const cli = new StrykerCli(process.argv);
156
157
// Run the CLI - will parse arguments and execute appropriate command
158
cli.run();
159
```
160
161
**Supported CLI Commands:**
162
163
- `run` - Execute mutation testing
164
- `init` - Initialize Stryker configuration for project
165
- `runServer` - Start mutation testing server (implements mutation-server-protocol)
166
167
168
## Types
169
170
The package relies on types from `@stryker-mutator/api/core`:
171
172
```typescript { .api }
173
// Key configuration interface - comprehensive configuration options
174
interface PartialStrykerOptions {
175
// Core testing configuration
176
testRunner?: string;
177
mutate?: string[];
178
reporters?: string[];
179
coverageAnalysis?: 'off' | 'all' | 'perTest';
180
181
// File and pattern configuration
182
files?: string[];
183
ignorePatterns?: string[];
184
ignoreStatic?: boolean;
185
186
// Test execution configuration
187
buildCommand?: string;
188
dryRunOnly?: boolean;
189
allowEmpty?: boolean;
190
checkers?: string[];
191
checkerNodeArgs?: string[];
192
testRunnerNodeArgs?: string[];
193
194
// Performance and concurrency
195
concurrency?: number;
196
maxConcurrentTestRunners?: number;
197
maxTestRunnerReuse?: number;
198
disableBail?: boolean;
199
200
// Timeout configuration
201
timeoutMS?: number;
202
timeoutFactor?: number;
203
dryRunTimeoutMinutes?: number;
204
205
// Incremental mutation testing
206
incremental?: boolean;
207
incrementalFile?: string;
208
force?: boolean;
209
210
// Thresholds and reporting
211
thresholds?: {
212
high?: number;
213
low?: number;
214
break?: number;
215
};
216
dashboard?: {
217
project?: string;
218
version?: string;
219
module?: string;
220
baseUrl?: string;
221
reportType?: 'full' | 'mutationScore';
222
};
223
224
// Directory and file management
225
inPlace?: boolean;
226
tempDirName?: string;
227
cleanTempDir?: boolean | 'always';
228
229
// Logging configuration
230
logLevel?: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'off';
231
fileLogLevel?: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'off';
232
allowConsoleColors?: boolean;
233
234
// Plugin configuration
235
plugins?: string[];
236
appendPlugins?: string[];
237
238
// Configuration file
239
configFile?: string;
240
241
// ... many other advanced configuration properties
242
}
243
244
// Result of mutation testing - key properties shown
245
interface MutantResult {
246
id: string;
247
mutatorName: string;
248
replacement: string;
249
fileName: string;
250
status: MutantStatus;
251
statusReason?: string;
252
// ... additional result properties from mutation-testing-report-schema
253
}
254
255
// Mutation status enumeration
256
type MutantStatus = 'Killed' | 'Survived' | 'NoCoverage' | 'TimedOut' | 'CompileError' | 'RuntimeError';
257
```
258
259
## CLI Binary
260
261
The package provides the `stryker` CLI binary as the primary interface for mutation testing:
262
263
```bash
264
# Run mutation testing (most common usage)
265
npx stryker run
266
267
# Initialize Stryker configuration
268
npx stryker init
269
270
# Start mutation testing server
271
npx stryker runServer
272
273
# Direct binary execution
274
./node_modules/.bin/stryker run
275
276
# Via npm script (add to package.json)
277
npm run stryker
278
279
# Global installation
280
npm install -g @stryker-mutator/core
281
stryker run
282
```
283
284
**Common CLI Options:**
285
286
```bash
287
# Specify files to mutate
288
stryker run --mutate "src/**/*.js" --testRunner jest
289
290
# Set coverage analysis strategy
291
stryker run --coverageAnalysis perTest
292
293
# Configure reporters
294
stryker run --reporters html,clear-text,progress
295
296
# Set concurrency
297
stryker run --concurrency 4
298
299
# Incremental mutation testing
300
stryker run --incremental
301
```
302
303
## Error Handling
304
305
The package handles errors through several mechanisms:
306
307
- **ConfigError**: Thrown for configuration validation issues
308
- **Promise Rejection**: `runMutationTest()` returns rejected promises for mutation testing failures
309
- **CLI Exit Codes**: CLI exits with code 1 on failures
310
- **Node Version Guard**: Throws errors for unsupported Node.js versions
311
312
```typescript
313
import { Stryker } from "@stryker-mutator/core";
314
315
try {
316
const stryker = new Stryker({
317
testRunner: 'jest',
318
mutate: ['src/**/*.js']
319
});
320
const results = await stryker.runMutationTest();
321
console.log(`Mutation testing completed: ${results.length} mutants tested`);
322
} catch (error) {
323
if (error.name === 'ConfigError') {
324
console.error('Configuration error:', error.message);
325
} else if (error.message.includes('Node.js version')) {
326
console.error('Node.js version incompatibility:', error.message);
327
} else {
328
console.error('Mutation testing failed:', error.message);
329
}
330
process.exit(1);
331
}