0
# Test Execution and Runner
1
2
Core test execution functionality providing the Mocha class for configuration and the Runner class for test execution with comprehensive lifecycle management and parallel execution support.
3
4
## Capabilities
5
6
### Mocha Class
7
8
Main test framework class for configuration and execution.
9
10
```javascript { .api }
11
/**
12
* Mocha constructor - creates a new test framework instance
13
* @param options - Configuration options object
14
*/
15
class Mocha {
16
constructor(options);
17
18
/**
19
* Add a test file to be loaded
20
* @param filepath - Path to test file
21
* @returns {Mocha} this - for chaining
22
*/
23
addFile(filepath);
24
25
/**
26
* Set the reporter for output formatting
27
* @param name - Reporter name or constructor function
28
* @param options - Reporter-specific options
29
* @returns {Mocha} this - for chaining
30
*/
31
reporter(name, options);
32
33
/**
34
* Set the test interface/UI
35
* @param name - Interface name: 'bdd', 'tdd', 'qunit', 'exports'
36
* @returns {Mocha} this - for chaining
37
*/
38
ui(name);
39
40
/**
41
* Set global timeout for all tests
42
* @param ms - Timeout in milliseconds, 0 to disable
43
* @returns {Mocha} this - for chaining
44
*/
45
timeout(ms);
46
47
/**
48
* Set threshold for slow test warnings
49
* @param ms - Slow threshold in milliseconds
50
* @returns {Mocha} this - for chaining
51
*/
52
slow(ms);
53
54
/**
55
* Set global retry count for failed tests
56
* @param count - Number of retries
57
* @returns {Mocha} this - for chaining
58
*/
59
retries(count);
60
61
/**
62
* Set grep pattern to filter tests
63
* @param pattern - String or RegExp pattern
64
* @returns {Mocha} this - for chaining
65
*/
66
grep(pattern);
67
68
/**
69
* Set fixed grep string (non-regex)
70
* @param string - Fixed string to match
71
* @returns {Mocha} this - for chaining
72
*/
73
fgrep(string);
74
75
/**
76
* Invert grep pattern matching
77
* @param invert - Whether to invert pattern matching
78
* @returns {Mocha} this - for chaining
79
*/
80
invert(invert);
81
82
/**
83
* Bail on first test failure
84
* @param bail - Whether to bail on first failure
85
* @returns {Mocha} this - for chaining
86
*/
87
bail(bail);
88
89
/**
90
* Enable/disable global leak detection
91
* @param checkLeaks - Whether to check for global leaks
92
* @returns {Mocha} this - for chaining
93
*/
94
checkLeaks(checkLeaks);
95
96
/**
97
* Set global variables to ignore during leak detection
98
* @param globals - Array of global variable names
99
* @returns {Mocha} this - for chaining
100
*/
101
globals(globals);
102
103
/**
104
* Run tests asynchronously only (no sync tests)
105
* @param asyncOnly - Whether to require async tests
106
* @returns {Mocha} this - for chaining
107
*/
108
asyncOnly(asyncOnly);
109
110
/**
111
* Allow uncaught exceptions to propagate
112
* @param allowUncaught - Whether to allow uncaught exceptions
113
* @returns {Mocha} this - for chaining
114
*/
115
allowUncaught(allowUncaught);
116
117
/**
118
* Add delay before running tests
119
* @param delay - Whether to delay test execution
120
* @returns {Mocha} this - for chaining
121
*/
122
delay(delay);
123
124
/**
125
* Forbid exclusive tests (.only)
126
* @param forbidOnly - Whether to forbid .only tests
127
* @returns {Mocha} this - for chaining
128
*/
129
forbidOnly(forbidOnly);
130
131
/**
132
* Forbid pending tests (.skip)
133
* @param forbidPending - Whether to forbid .skip tests
134
* @returns {Mocha} this - for chaining
135
*/
136
forbidPending(forbidPending);
137
138
/**
139
* Show full stack traces
140
* @param fullTrace - Whether to show full stack traces
141
* @returns {Mocha} this - for chaining
142
*/
143
fullTrace(fullTrace);
144
145
/**
146
* Enable colored output
147
* @param color - Whether to enable colored output
148
* @returns {Mocha} this - for chaining
149
*/
150
color(color);
151
152
/**
153
* Show inline diffs
154
* @param inlineDiffs - Whether to show inline diffs
155
* @returns {Mocha} this - for chaining
156
*/
157
inlineDiffs(inlineDiffs);
158
159
/**
160
* Show diff on test failure
161
* @param diff - Whether to show diffs
162
* @returns {Mocha} this - for chaining
163
*/
164
diff(diff);
165
166
/**
167
* Perform dry run (don't execute tests)
168
* @param dryRun - Whether to perform dry run
169
* @returns {Mocha} this - for chaining
170
*/
171
dryRun(dryRun);
172
173
/**
174
* Enable parallel test execution
175
* @param parallel - Whether to run tests in parallel
176
* @returns {Mocha} this - for chaining
177
*/
178
parallelMode(parallel);
179
180
/**
181
* Set root hooks (global setup/teardown)
182
* @param hooks - Root hook functions
183
* @returns {Mocha} this - for chaining
184
*/
185
rootHooks(hooks);
186
187
/**
188
* Set global setup function
189
* @param fn - Global setup function
190
* @returns {Mocha} this - for chaining
191
*/
192
globalSetup(fn);
193
194
/**
195
* Set global teardown function
196
* @param fn - Global teardown function
197
* @returns {Mocha} this - for chaining
198
*/
199
globalTeardown(fn);
200
201
/**
202
* Load test files into memory
203
* @returns {Mocha} this - for chaining
204
*/
205
loadFiles();
206
207
/**
208
* Load test files asynchronously
209
* @returns {Promise<Mocha>} Promise resolving to this instance
210
*/
211
loadFilesAsync();
212
213
/**
214
* Unload test files from memory
215
* @returns {Mocha} this - for chaining
216
*/
217
unloadFiles();
218
219
/**
220
* Run all loaded tests
221
* @param callback - Completion callback receiving failure count
222
* @returns {Runner} Runner instance
223
*/
224
run(callback);
225
226
/**
227
* Dispose of this Mocha instance
228
*/
229
dispose();
230
}
231
```
232
233
**Usage Example:**
234
235
```javascript
236
const Mocha = require('mocha');
237
238
const mocha = new Mocha({
239
ui: 'bdd',
240
reporter: 'spec',
241
timeout: 5000,
242
slow: 100
243
});
244
245
// Add test files
246
mocha.addFile('./test/unit/helpers.js');
247
mocha.addFile('./test/unit/models.js');
248
249
// Configure additional options
250
mocha
251
.grep('User')
252
.bail(true)
253
.checkLeaks(true);
254
255
// Run tests
256
mocha.run(function(failures) {
257
console.log(`Tests completed with ${failures} failures`);
258
process.exitCode = failures ? 1 : 0;
259
});
260
```
261
262
### Runner Class
263
264
Test execution engine that manages the test lifecycle and emits events.
265
266
```javascript { .api }
267
/**
268
* Runner class - manages test execution
269
* Extends EventEmitter for test lifecycle events
270
*/
271
class Runner extends EventEmitter {
272
/**
273
* Run all tests
274
* @param callback - Completion callback
275
* @returns {Runner} this - for chaining
276
*/
277
run(callback);
278
279
/**
280
* Abort test execution
281
* @returns {Runner} this - for chaining
282
*/
283
abort();
284
285
/**
286
* Set grep pattern for filtering tests
287
* @param pattern - String or RegExp pattern
288
* @returns {Runner} this - for chaining
289
*/
290
grep(pattern);
291
292
/**
293
* Get current test count statistics
294
* @returns {Object} Test count statistics
295
*/
296
stats;
297
298
/**
299
* Check if runner is running
300
* @returns {boolean} Whether runner is currently executing
301
*/
302
isRunning();
303
}
304
```
305
306
### Runner Events
307
308
The Runner emits events throughout the test lifecycle that reporters use:
309
310
```javascript { .api }
311
// Test execution lifecycle events
312
const EVENTS = {
313
EVENT_RUN_BEGIN: 'start', // Test run starts
314
EVENT_RUN_END: 'end', // Test run ends
315
EVENT_SUITE_BEGIN: 'suite', // Suite starts
316
EVENT_SUITE_END: 'suite end', // Suite ends
317
EVENT_TEST_BEGIN: 'test', // Individual test starts
318
EVENT_TEST_END: 'test end', // Individual test ends
319
EVENT_TEST_PASS: 'pass', // Test passes
320
EVENT_TEST_FAIL: 'fail', // Test fails
321
EVENT_TEST_PENDING: 'pending', // Test is pending/skipped
322
EVENT_HOOK_BEGIN: 'hook', // Hook starts
323
EVENT_HOOK_END: 'hook end' // Hook ends
324
};
325
```
326
327
**Usage Example:**
328
329
```javascript
330
const runner = mocha.run();
331
332
runner.on('start', function() {
333
console.log('Test run started');
334
});
335
336
runner.on('pass', function(test) {
337
console.log(`✓ ${test.title}`);
338
});
339
340
runner.on('fail', function(test, err) {
341
console.log(`✗ ${test.title}: ${err.message}`);
342
});
343
344
runner.on('end', function() {
345
console.log('Test run completed');
346
});
347
```
348
349
### Parallel Execution
350
351
Mocha supports parallel test execution for improved performance:
352
353
```javascript { .api }
354
/**
355
* Enable parallel execution
356
* @param options - Parallel execution options
357
*/
358
const mocha = new Mocha({
359
parallel: true,
360
jobs: 4 // Number of worker processes
361
});
362
363
/**
364
* Parallel execution configuration
365
*/
366
interface ParallelOptions {
367
parallel: boolean; // Enable parallel execution
368
jobs?: number; // Number of workers (default: CPU count - 1)
369
timeout?: number; // Worker timeout
370
}
371
```
372
373
### Asynchronous Test Support
374
375
Mocha supports multiple patterns for asynchronous tests:
376
377
```javascript { .api }
378
/**
379
* Test function signatures for different async patterns
380
*/
381
382
// Promise-based tests
383
function testFunction(): Promise<any>;
384
385
// Callback-based tests
386
function testFunction(done: DoneCB): void;
387
388
// Async/await tests
389
async function testFunction(): Promise<any>;
390
391
type DoneCB = (error?: any) => void;
392
```
393
394
**Usage Examples:**
395
396
```javascript
397
// Promise-based
398
it('should handle promises', function() {
399
return new Promise((resolve) => {
400
setTimeout(resolve, 100);
401
});
402
});
403
404
// Callback-based
405
it('should handle callbacks', function(done) {
406
setTimeout(() => {
407
done();
408
}, 100);
409
});
410
411
// Async/await
412
it('should handle async/await', async function() {
413
await new Promise(resolve => setTimeout(resolve, 100));
414
});
415
```
416
417
### Context and Test State
418
419
Each test receives a context object with utilities:
420
421
```javascript { .api }
422
/**
423
* Test context object (this in test functions)
424
*/
425
interface Context {
426
test?: Test; // Current test object
427
currentTest?: Test; // Alias for test
428
timeout(ms?: number): number | Context; // Set/get timeout
429
slow(ms?: number): number | Context; // Set/get slow threshold
430
skip(): never; // Skip current test
431
retries(count?: number): number | Context; // Set/get retry count
432
}
433
```
434
435
**Usage Example:**
436
437
```javascript
438
it('should use context methods', function() {
439
this.timeout(10000); // Set timeout for this test
440
this.slow(1000); // Set slow threshold
441
442
// Conditionally skip test
443
if (process.env.SKIP_SLOW) {
444
this.skip();
445
}
446
447
// Retry on failure
448
this.retries(3);
449
});
450
```
451
452
### Test File Loading
453
454
Mocha provides methods for loading and managing test files:
455
456
```javascript { .api }
457
/**
458
* Load test files synchronously
459
*/
460
mocha.loadFiles();
461
462
/**
463
* Load test files asynchronously
464
* @returns {Promise<Mocha>} Promise resolving when files are loaded
465
*/
466
mocha.loadFilesAsync();
467
468
/**
469
* Unload test files from require cache
470
*/
471
mocha.unloadFiles();
472
473
/**
474
* Add files to be loaded
475
* @param filepath - Path to test file
476
*/
477
mocha.addFile(filepath);
478
479
/**
480
* Get list of files to be loaded
481
* @returns {string[]} Array of file paths
482
*/
483
mocha.files;
484
```