0
# Environment and Configuration
1
2
Jasmine's test execution environment management including configuration options, randomization settings, timeout controls, and execution flow customization.
3
4
## Capabilities
5
6
### Environment Access
7
8
Functions for accessing and managing the Jasmine test environment.
9
10
```javascript { .api }
11
/**
12
* Get the current Jasmine environment instance
13
* @param options - Optional configuration for environment creation
14
* @returns Environment instance
15
*/
16
jasmine.getEnv(options?: { suppressLoadErrors?: boolean }): Environment;
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
// Get the default environment
23
const env = jasmine.getEnv();
24
25
// Get environment with error suppression
26
const env = jasmine.getEnv({ suppressLoadErrors: true });
27
28
// Configure and execute tests
29
env.configure({
30
random: true,
31
seed: '12345'
32
});
33
env.execute();
34
```
35
36
### Environment Configuration
37
38
Methods for configuring test execution behavior.
39
40
```javascript { .api }
41
interface Environment {
42
/**
43
* Configure the test environment with options
44
* @param options - Configuration options object
45
*/
46
configure(options: EnvConfig): void;
47
48
/**
49
* Execute the test suite
50
* @param runnableIds - Optional array of specific runnable IDs to execute
51
*/
52
execute(runnableIds?: string[]): void;
53
54
/**
55
* Add a reporter to receive test results
56
* @param reporter - Reporter instance
57
*/
58
addReporter(reporter: Reporter): void;
59
60
/**
61
* Remove a reporter
62
* @param reporter - Reporter instance to remove
63
*/
64
removeReporter(reporter: Reporter): void;
65
66
/**
67
* Set the order of spec execution
68
* @param order - Order function or 'random'
69
*/
70
randomizeTests(seed?: string): void;
71
72
/**
73
* Get configuration value
74
* @param key - Configuration key
75
* @returns Configuration value
76
*/
77
configuration(): EnvConfig;
78
}
79
```
80
81
**Usage Examples:**
82
83
```javascript
84
const env = jasmine.getEnv();
85
86
// Configure environment
87
env.configure({
88
random: true,
89
seed: '67890',
90
stopOnSpecFailure: false,
91
failSpecWithNoExpectations: true,
92
stopSpecOnExpectationFailure: false
93
});
94
95
// Add custom reporter
96
const customReporter = {
97
specDone: (result) => {
98
console.log(`Spec: ${result.fullName} - ${result.status}`);
99
}
100
};
101
env.addReporter(customReporter);
102
103
// Execute specific tests
104
env.execute(['spec-1', 'spec-2']);
105
106
// Get current configuration
107
const config = env.configuration();
108
console.log('Random execution:', config.random);
109
```
110
111
### Configuration Options
112
113
Configuration object interface and available options.
114
115
```javascript { .api }
116
interface EnvConfig {
117
/**
118
* Randomize the order of execution of specs (default: true)
119
*/
120
random?: boolean;
121
122
/**
123
* Seed for randomization (default: random)
124
* Can be string or number
125
*/
126
seed?: string | number;
127
128
/**
129
* Stop executing specs after the first failure (default: false)
130
*/
131
stopOnSpecFailure?: boolean;
132
133
/**
134
* Fail specs that have no expectations (default: false)
135
*/
136
failSpecWithNoExpectations?: boolean;
137
138
/**
139
* Stop executing a spec after the first expectation failure (default: false)
140
*/
141
stopSpecOnExpectationFailure?: boolean;
142
143
/**
144
* Hide disabled specs from results (default: false)
145
*/
146
hideDisabled?: boolean;
147
148
/**
149
* Spec filter function to determine which specs to run
150
*/
151
specFilter?: (spec: Spec) => boolean;
152
153
/**
154
* Promise timeout for async specs in milliseconds
155
*/
156
asyncTimeout?: number;
157
}
158
```
159
160
**Usage Examples:**
161
162
```javascript
163
// Conservative configuration for CI
164
jasmine.getEnv().configure({
165
random: false, // Deterministic order
166
stopOnSpecFailure: true, // Fail fast
167
failSpecWithNoExpectations: true, // Ensure all specs have assertions
168
stopSpecOnExpectationFailure: false
169
});
170
171
// Development configuration
172
jasmine.getEnv().configure({
173
random: true,
174
seed: Date.now().toString(), // Different seed each run
175
hideDisabled: true, // Hide disabled specs
176
asyncTimeout: 10000 // 10 second timeout for async
177
});
178
179
// Custom spec filtering
180
jasmine.getEnv().configure({
181
specFilter: (spec) => {
182
// Only run specs with 'integration' in the name
183
return spec.getFullName().includes('integration');
184
}
185
});
186
```
187
188
### Global Configuration Constants
189
190
Pre-defined constants for common configuration values.
191
192
```javascript { .api }
193
/**
194
* Default timeout interval for asynchronous operations (5000ms)
195
*/
196
jasmine.DEFAULT_TIMEOUT_INTERVAL: number;
197
198
/**
199
* Maximum depth for pretty-printing nested objects (8 levels)
200
*/
201
jasmine.MAX_PRETTY_PRINT_DEPTH: number;
202
203
/**
204
* Maximum length for pretty-printing arrays (50 elements)
205
*/
206
jasmine.MAX_PRETTY_PRINT_ARRAY_LENGTH: number;
207
208
/**
209
* Maximum number of characters for pretty-printing (1000 chars)
210
*/
211
jasmine.MAX_PRETTY_PRINT_CHARS: number;
212
```
213
214
**Usage Examples:**
215
216
```javascript
217
// Check default values
218
console.log('Default timeout:', jasmine.DEFAULT_TIMEOUT_INTERVAL); // 5000
219
220
// Modify global constants (affects all pretty-printing)
221
jasmine.MAX_PRETTY_PRINT_DEPTH = 5;
222
jasmine.MAX_PRETTY_PRINT_ARRAY_LENGTH = 25;
223
jasmine.MAX_PRETTY_PRINT_CHARS = 500;
224
225
// Use in test timeouts
226
it('should handle slow operation', (done) => {
227
slowOperation(() => {
228
expect(true).toBe(true);
229
done();
230
});
231
}, jasmine.DEFAULT_TIMEOUT_INTERVAL * 2); // 10 second timeout
232
```
233
234
### Spec and Suite Filtering
235
236
Methods for controlling which tests execute.
237
238
```javascript { .api }
239
interface Environment {
240
/**
241
* Set a filter function to determine which specs run
242
* @param filterFn - Function that returns true for specs to run
243
*/
244
specFilter(filterFn: (spec: Spec) => boolean): void;
245
}
246
```
247
248
**Usage Examples:**
249
250
```javascript
251
const env = jasmine.getEnv();
252
253
// Run only specs containing 'unit' in their name
254
env.specFilter((spec) => {
255
return spec.getFullName().toLowerCase().includes('unit');
256
});
257
258
// Run specs based on custom metadata
259
env.specFilter((spec) => {
260
const suite = spec.parentSuite;
261
return suite && suite.description.includes('API');
262
});
263
264
// Complex filtering logic
265
env.specFilter((spec) => {
266
const fullName = spec.getFullName();
267
const isIntegration = fullName.includes('integration');
268
const isUnit = fullName.includes('unit');
269
const runIntegration = process.env.RUN_INTEGRATION === 'true';
270
271
return runIntegration ? isIntegration : isUnit;
272
});
273
```
274
275
### Execution Control
276
277
Methods for controlling test execution flow.
278
279
```javascript { .api }
280
interface Environment {
281
/**
282
* Throw errors instead of just failing specs
283
* @param value - Whether to throw on expectation failure
284
*/
285
throwOnExpectationFailure(value: boolean): void;
286
287
/**
288
* Stop execution after first spec failure
289
* @param value - Whether to stop on first failure
290
*/
291
stopOnSpecFailure(value: boolean): void;
292
293
/**
294
* Set random seed for test execution order
295
* @param seed - Seed value for randomization
296
*/
297
seed(seed: string | number): void;
298
299
/**
300
* Enable or disable random execution order
301
* @param value - Whether to randomize execution
302
*/
303
randomizeTests(value: boolean): void;
304
}
305
```
306
307
**Usage Examples:**
308
309
```javascript
310
const env = jasmine.getEnv();
311
312
// For debugging - throw on first failure
313
env.throwOnExpectationFailure(true);
314
env.stopOnSpecFailure(true);
315
316
// Set specific seed for reproducible runs
317
env.seed('test-seed-123');
318
env.randomizeTests(true);
319
320
// Disable randomization for debugging
321
env.randomizeTests(false);
322
```
323
324
### Environment Events and Hooks
325
326
Methods for hooking into environment lifecycle events.
327
328
```javascript { .api }
329
interface Environment {
330
/**
331
* Add a callback to be called before all specs
332
* @param fn - Function to call
333
*/
334
beforeAll(fn: () => void | Promise<void>): void;
335
336
/**
337
* Add a callback to be called after all specs
338
* @param fn - Function to call
339
*/
340
afterAll(fn: () => void | Promise<void>): void;
341
}
342
```
343
344
**Usage Examples:**
345
346
```javascript
347
const env = jasmine.getEnv();
348
349
// Global setup
350
env.beforeAll(async () => {
351
console.log('Starting test suite...');
352
await setupTestDatabase();
353
await seedTestData();
354
});
355
356
// Global teardown
357
env.afterAll(async () => {
358
console.log('Test suite completed');
359
await cleanupTestDatabase();
360
await closeConnections();
361
});
362
```
363
364
### Reporter Interface
365
366
Interface for custom reporters that receive test results.
367
368
```javascript { .api }
369
interface Reporter {
370
/** Called when Jasmine starts running */
371
jasmineStarted?(suiteInfo: SuiteInfo): void;
372
373
/** Called when a suite starts */
374
suiteStarted?(result: SuiteResult): void;
375
376
/** Called when a spec starts */
377
specStarted?(result: SpecResult): void;
378
379
/** Called when a spec is done */
380
specDone?(result: SpecResult): void;
381
382
/** Called when a suite is done */
383
suiteDone?(result: SuiteResult): void;
384
385
/** Called when Jasmine is done running */
386
jasmineDone?(runDetails: RunDetails): void;
387
}
388
389
interface SuiteInfo {
390
totalSpecsDefined: number;
391
}
392
393
interface RunDetails {
394
overallStatus: 'passed' | 'failed' | 'incomplete';
395
totalTime: number;
396
incompleteReason?: string;
397
}
398
```
399
400
**Usage Examples:**
401
402
```javascript
403
// Custom console reporter
404
const customReporter = {
405
jasmineStarted: (suiteInfo) => {
406
console.log(`Running ${suiteInfo.totalSpecsDefined} specs`);
407
},
408
409
specStarted: (result) => {
410
console.log(`Starting: ${result.fullName}`);
411
},
412
413
specDone: (result) => {
414
const status = result.status === 'passed' ? '✓' : '✗';
415
console.log(`${status} ${result.fullName}`);
416
417
if (result.status === 'failed') {
418
result.failedExpectations.forEach(failure => {
419
console.log(` Error: ${failure.message}`);
420
});
421
}
422
},
423
424
jasmineDone: (runDetails) => {
425
console.log(`Tests completed: ${runDetails.overallStatus}`);
426
console.log(`Total time: ${runDetails.totalTime}ms`);
427
}
428
};
429
430
jasmine.getEnv().addReporter(customReporter);
431
```
432
433
## Types
434
435
```javascript { .api }
436
interface Environment {
437
configure(options: EnvConfig): void;
438
execute(runnableIds?: string[]): void;
439
addReporter(reporter: Reporter): void;
440
removeReporter(reporter: Reporter): void;
441
specFilter(filterFn: (spec: Spec) => boolean): void;
442
randomizeTests(value: boolean): void;
443
seed(seed: string | number): void;
444
configuration(): EnvConfig;
445
}
446
447
interface EnvConfig {
448
random?: boolean;
449
seed?: string | number;
450
stopOnSpecFailure?: boolean;
451
failSpecWithNoExpectations?: boolean;
452
stopSpecOnExpectationFailure?: boolean;
453
hideDisabled?: boolean;
454
specFilter?: (spec: Spec) => boolean;
455
asyncTimeout?: number;
456
}
457
458
interface SuiteResult {
459
id: string;
460
description: string;
461
fullName: string;
462
status?: string;
463
properties?: { [key: string]: any };
464
}
465
466
interface SpecResult {
467
id: string;
468
description: string;
469
fullName: string;
470
status: 'passed' | 'failed' | 'pending';
471
failedExpectations: ExpectationResult[];
472
passedExpectations: ExpectationResult[];
473
pendingReason?: string;
474
properties?: { [key: string]: any };
475
}
476
```