0
# Jest Integration
1
2
Setup functions that integrate Jest-specific features like snapshots, expect matchers, global utilities, and parameterized testing.
3
4
## Capabilities
5
6
### Jest Globals Setup
7
8
Main function that sets up Jest-specific globals including snapshots, expect matchers, and serializers.
9
10
```typescript { .api }
11
/**
12
* Sets up Jest globals and snapshot functionality
13
* Configures snapshot state, serializers, and expect integration
14
* @param options - Configuration options for Jest globals setup
15
* @returns Promise resolving to configured SnapshotState
16
*/
17
function setupJestGlobals(options: SetupOptions): Promise<SnapshotState>;
18
19
/**
20
* Configuration options for Jest globals setup
21
*/
22
interface SetupOptions {
23
/** Jest project configuration */
24
config: Config.ProjectConfig;
25
/** Jest global configuration */
26
globalConfig: Config.GlobalConfig;
27
/** Local require function for loading modules */
28
localRequire: (moduleName: string) => Plugin;
29
/** Path to the test file being executed */
30
testPath: string;
31
}
32
```
33
34
### Snapshot State Management
35
36
Integration with Jest's snapshot testing system.
37
38
```typescript { .api }
39
/**
40
* Snapshot state management for test files
41
* Handles snapshot creation, matching, and cleanup
42
*/
43
interface SnapshotState {
44
/** Number of snapshots added during test run */
45
added: number;
46
/** Number of snapshots matched during test run */
47
matched: number;
48
/** Number of snapshots that didn't match */
49
unmatched: number;
50
/** Number of snapshots updated during test run */
51
updated: number;
52
53
/** Mark snapshots as checked for a specific test */
54
markSnapshotsAsCheckedForTest(testName: string): void;
55
56
/** Get count of unchecked snapshots */
57
getUncheckedCount(): number;
58
59
/** Get keys of unchecked snapshots */
60
getUncheckedKeys(): Array<string>;
61
62
/** Remove unchecked snapshot keys */
63
removeUncheckedKeys(): void;
64
65
/** Save snapshot state and return status */
66
save(): { deleted: boolean };
67
}
68
```
69
70
### Jest-Each Integration
71
72
Installs parameterized testing functionality using jest-each.
73
74
```typescript { .api }
75
/**
76
* Installs jest-each parameterized testing functionality
77
* Adds .each method to test and describe functions
78
* @param environment - Jest test environment to enhance
79
*/
80
function installEach(environment: JestEnvironment): void;
81
```
82
83
### Error Handling Integration
84
85
Integration with Jest's error handling and private API protection.
86
87
```typescript { .api }
88
/**
89
* Installs error handling for deprecated/private Jasmine APIs
90
* Throws errors when deprecated features are used if errorOnDeprecated is enabled
91
* @param global - Global object to install error handling into
92
*/
93
function installErrorOnPrivate(global: Global.Global): void;
94
```
95
96
### Expect Integration
97
98
Integration with Jest's expect assertion library.
99
100
```typescript { .api }
101
/**
102
* Jest expect integration setup
103
* Configures expect matchers and assertion handling
104
*/
105
interface ExpectIntegration {
106
/** Set up expect with configuration */
107
setupExpect(options: { expand: boolean }): void;
108
109
/** Extract expected assertion errors */
110
extractExpectedAssertionsErrors(): Array<{
111
actual: string;
112
expected: string;
113
error: Error;
114
}>;
115
116
/** Get suppressed errors from expect */
117
getSuppressedErrors(): Array<Error>;
118
119
/** Set expect state */
120
setState(state: {
121
currentTestName?: string;
122
snapshotState?: SnapshotState;
123
testPath?: string;
124
suppressedErrors?: Array<Error>;
125
}): void;
126
}
127
```
128
129
## Integration Features
130
131
### Parameterized Testing
132
133
Jest-each integration allows parameterized tests with table-driven data.
134
135
**Usage Examples:**
136
137
```typescript
138
// Parameterized it tests
139
it.each([
140
[1, 2, 3],
141
[2, 3, 5],
142
[3, 4, 7]
143
])("should add %i + %i = %i", (a, b, expected) => {
144
expect(a + b).toBe(expected);
145
});
146
147
// Parameterized describe blocks
148
describe.each([
149
["positive", 1],
150
["negative", -1],
151
["zero", 0]
152
])("number behavior: %s", (description, value) => {
153
it(`should handle ${description} numbers`, () => {
154
expect(typeof value).toBe("number");
155
});
156
});
157
158
// Object-based parameterization
159
it.each([
160
{ a: 1, b: 2, expected: 3 },
161
{ a: 2, b: 3, expected: 5 }
162
])("should add $a + $b = $expected", ({ a, b, expected }) => {
163
expect(a + b).toBe(expected);
164
});
165
```
166
167
### Concurrent Test Parameterization
168
169
Integration with concurrent testing for parameterized tests.
170
171
**Usage Examples:**
172
173
```typescript
174
// Concurrent parameterized tests
175
it.concurrent.each([
176
[1, 100],
177
[2, 200],
178
[3, 300]
179
])("should process %i to get %i", async (input, expected) => {
180
const result = await processAsync(input);
181
expect(result).toBe(expected);
182
});
183
```
184
185
### Snapshot Testing Integration
186
187
Automatic setup of snapshot testing capabilities.
188
189
**Usage Examples:**
190
191
```typescript
192
// Snapshot testing works automatically
193
it("should match snapshot", () => {
194
const data = { name: "test", value: 42 };
195
expect(data).toMatchSnapshot();
196
});
197
198
// Inline snapshots
199
it("should match inline snapshot", () => {
200
const result = formatData({ id: 1, name: "test" });
201
expect(result).toMatchInlineSnapshot(`
202
Object {
203
"formatted": "test (1)",
204
}
205
`);
206
});
207
```
208
209
### Custom Serializers
210
211
Support for custom snapshot serializers.
212
213
```typescript { .api }
214
/**
215
* Snapshot serializer plugin interface
216
*/
217
interface Plugin {
218
/** Test if this serializer should handle the value */
219
test(val: any): boolean;
220
/** Serialize the value to a string */
221
serialize(val: any, config: any, indentation: string, depth: number, refs: any): string;
222
}
223
```
224
225
**Usage Examples:**
226
227
```typescript
228
// Custom serializer in Jest config
229
module.exports = {
230
snapshotSerializers: [
231
"my-custom-serializer",
232
"<rootDir>/custom-serializer.js"
233
]
234
};
235
236
// Custom serializer implementation
237
module.exports = {
238
test(val) {
239
return val && val.constructor && val.constructor.name === "MyClass";
240
},
241
serialize(val) {
242
return `MyClass { value: ${val.value} }`;
243
}
244
};
245
```
246
247
### Global Timeout Configuration
248
249
Integration with Jest's timeout configuration.
250
251
**Usage Examples:**
252
253
```typescript
254
// Global timeout in Jest config
255
module.exports = {
256
testTimeout: 10000, // 10 second default timeout
257
};
258
259
// Per-test timeout
260
it("should complete quickly", async () => {
261
await fastOperation();
262
}, 1000); // 1 second timeout
263
264
// Jasmine-style timeout configuration
265
beforeEach(() => {
266
jasmine.DEFAULT_TIMEOUT_INTERVAL = 15000;
267
});
268
```
269
270
### Mock Integration
271
272
Integration with Jest's mocking system for module and function mocks.
273
274
**Usage Examples:**
275
276
```typescript
277
// Module mocking works automatically
278
jest.mock("./my-module");
279
280
// Function mocking
281
const mockFn = jest.fn();
282
mockFn.mockReturnValue("mocked value");
283
284
// Spy integration with Jasmine spies
285
const spy = spyOn(obj, "method");
286
expect(spy).toHaveBeenCalled();
287
```
288
289
### Setup Files Integration
290
291
Support for Jest's setup files configuration.
292
293
**Usage Examples:**
294
295
```typescript
296
// Jest config with setup files
297
module.exports = {
298
setupFilesAfterEnv: [
299
"<rootDir>/setup-tests.js",
300
"<rootDir>/custom-matchers.js"
301
]
302
};
303
304
// Setup file example (setup-tests.js)
305
import "jest-extended"; // Additional matchers
306
307
// Custom matcher
308
expect.extend({
309
toBeWithinRange(received, floor, ceiling) {
310
const pass = received >= floor && received <= ceiling;
311
return {
312
pass,
313
message: () =>
314
`expected ${received} to be within range ${floor} - ${ceiling}`
315
};
316
}
317
});
318
```
319
320
### Environment Integration
321
322
Integration with different Jest test environments.
323
324
**Usage Examples:**
325
326
```typescript
327
// Jest config with environment
328
module.exports = {
329
testEnvironment: "jsdom", // or "node"
330
testEnvironmentOptions: {
331
url: "http://localhost"
332
}
333
};
334
335
// Environment-specific globals are available
336
if (typeof window !== "undefined") {
337
// Browser/jsdom environment
338
expect(window.location.href).toBe("http://localhost/");
339
} else {
340
// Node environment
341
expect(process.env.NODE_ENV).toBeDefined();
342
}
343
```
344
345
## Configuration Integration
346
347
Jest-jasmine2 integrates with various Jest configuration options:
348
349
### Project Configuration
350
351
- `snapshotSerializers`: Custom snapshot serializers
352
- `setupFilesAfterEnv`: Setup files to run after environment creation
353
- `testLocationInResults`: Include test location information in results
354
- `fakeTimers`: Fake timer configuration
355
- `resetModules`/`clearMocks`/`resetMocks`/`restoreMocks`: Mock behavior settings
356
357
### Global Configuration
358
359
- `expand`: Expand diff output in assertion failures
360
- `updateSnapshot`: Update snapshots during test run
361
- `testTimeout`: Default timeout for all tests
362
- `maxConcurrency`: Maximum concurrent tests for it.concurrent
363
- `errorOnDeprecated`: Error on usage of deprecated APIs
364
365
**Usage Examples:**
366
367
```typescript
368
// Complete Jest configuration for jest-jasmine2
369
module.exports = {
370
testRunner: "jest-jasmine2",
371
testEnvironment: "node",
372
testTimeout: 10000,
373
maxConcurrency: 4,
374
setupFilesAfterEnv: ["<rootDir>/setup.js"],
375
snapshotSerializers: ["my-serializer"],
376
fakeTimers: {
377
enableGlobally: true,
378
legacyFakeTimers: false
379
},
380
clearMocks: true,
381
resetMocks: false,
382
restoreMocks: true
383
};
384
```