0
# Expectations and Matchers
1
2
Jasmine's assertion system for verifying expected behavior. Includes synchronous and asynchronous expectations with a comprehensive set of built-in matchers for various data types and scenarios.
3
4
## Capabilities
5
6
### Expectation Functions
7
8
Core functions for creating expectations and assertions.
9
10
```javascript { .api }
11
/**
12
* Create an expectation for synchronous testing
13
* @param actual - The actual value to test
14
* @returns Expectation object with matcher methods
15
*/
16
function expect(actual: any): Expectation;
17
18
/**
19
* Create an expectation for asynchronous testing (promises)
20
* @param actual - The promise or async function to test
21
* @returns AsyncExpectation object with async matcher methods
22
*/
23
function expectAsync(actual: Promise<any> | (() => Promise<any>)): AsyncExpectation;
24
```
25
26
**Usage Examples:**
27
28
```javascript
29
// Synchronous expectations
30
expect(5).toBe(5);
31
expect([1, 2, 3]).toContain(2);
32
expect('hello world').toMatch(/world/);
33
34
// Asynchronous expectations
35
await expectAsync(fetchData()).toBeResolved();
36
await expectAsync(failingPromise()).toBeRejectedWith('Error message');
37
```
38
39
### Equality Matchers
40
41
Matchers for testing equality and identity.
42
43
```javascript { .api }
44
interface Expectation {
45
/**
46
* Strict equality comparison using ===
47
* @param expected - Expected value
48
*/
49
toBe(expected: any): boolean;
50
51
/**
52
* Negated toBe matcher
53
* @param expected - Value that should not match
54
*/
55
not.toBe(expected: any): boolean;
56
57
/**
58
* Deep equality comparison for objects and arrays
59
* @param expected - Expected value or structure
60
*/
61
toEqual(expected: any): boolean;
62
63
/**
64
* Negated toEqual matcher
65
* @param expected - Value that should not equal
66
*/
67
not.toEqual(expected: any): boolean;
68
}
69
```
70
71
**Usage Examples:**
72
73
```javascript
74
// Identity comparison
75
expect(obj1).toBe(obj1); // same reference
76
expect(5).toBe(5);
77
expect('hello').not.toBe('world');
78
79
// Value comparison
80
expect({a: 1}).toEqual({a: 1}); // different objects, same structure
81
expect([1, 2, 3]).toEqual([1, 2, 3]);
82
expect({a: 1}).not.toEqual({a: 2});
83
```
84
85
### Truthiness Matchers
86
87
Matchers for testing boolean values and truthiness.
88
89
```javascript { .api }
90
interface Expectation {
91
/** Test if value is truthy */
92
toBeTruthy(): boolean;
93
94
/** Test if value is falsy */
95
toBeFalsy(): boolean;
96
97
/** Test if value is exactly true */
98
toBeTrue(): boolean;
99
100
/** Test if value is exactly false */
101
toBeFalse(): boolean;
102
103
/** Test if value is not undefined */
104
toBeDefined(): boolean;
105
106
/** Test if value is undefined */
107
toBeUndefined(): boolean;
108
109
/** Test if value is null */
110
toBeNull(): boolean;
111
}
112
```
113
114
**Usage Examples:**
115
116
```javascript
117
expect(true).toBeTruthy();
118
expect(1).toBeTruthy();
119
expect('hello').toBeTruthy();
120
121
expect(false).toBeFalsy();
122
expect(0).toBeFalsy();
123
expect('').toBeFalsy();
124
125
expect(true).toBeTrue();
126
expect(false).toBeFalse();
127
128
expect(someValue).toBeDefined();
129
expect(undefined).toBeUndefined();
130
expect(null).toBeNull();
131
```
132
133
### Numeric Matchers
134
135
Matchers for numeric comparisons and special numeric values.
136
137
```javascript { .api }
138
interface Expectation {
139
/**
140
* Test floating point approximation
141
* @param expected - Expected numeric value
142
* @param precision - Optional decimal places for precision (default: 2)
143
*/
144
toBeCloseTo(expected: number, precision?: number): boolean;
145
146
/** Test if value is greater than expected */
147
toBeGreaterThan(expected: number): boolean;
148
149
/** Test if value is greater than or equal to expected */
150
toBeGreaterThanOrEqual(expected: number): boolean;
151
152
/** Test if value is less than expected */
153
toBeLessThan(expected: number): boolean;
154
155
/** Test if value is less than or equal to expected */
156
toBeLessThanOrEqual(expected: number): boolean;
157
158
/** Test if value is NaN */
159
toBeNaN(): boolean;
160
161
/** Test if value is positive infinity */
162
toBePositiveInfinity(): boolean;
163
164
/** Test if value is negative infinity */
165
toBeNegativeInfinity(): boolean;
166
}
167
```
168
169
**Usage Examples:**
170
171
```javascript
172
expect(3.14159).toBeCloseTo(3.14, 2);
173
expect(0.1 + 0.2).toBeCloseTo(0.3);
174
175
expect(10).toBeGreaterThan(5);
176
expect(10).toBeGreaterThanOrEqual(10);
177
expect(5).toBeLessThan(10);
178
expect(5).toBeLessThanOrEqual(5);
179
180
expect(NaN).toBeNaN();
181
expect(Infinity).toBePositiveInfinity();
182
expect(-Infinity).toBeNegativeInfinity();
183
```
184
185
### Type and Instance Matchers
186
187
Matchers for testing object types and instanceof relationships.
188
189
```javascript { .api }
190
interface Expectation {
191
/**
192
* Test if value is an instance of expected constructor
193
* @param expected - Constructor function
194
*/
195
toBeInstanceOf(expected: Function): boolean;
196
}
197
```
198
199
**Usage Examples:**
200
201
```javascript
202
expect(new Date()).toBeInstanceOf(Date);
203
expect([]).toBeInstanceOf(Array);
204
expect(/regex/).toBeInstanceOf(RegExp);
205
expect(new Error()).toBeInstanceOf(Error);
206
207
class CustomClass {}
208
const instance = new CustomClass();
209
expect(instance).toBeInstanceOf(CustomClass);
210
```
211
212
### Container Matchers
213
214
Matchers for testing arrays, strings, and collections.
215
216
```javascript { .api }
217
interface Expectation {
218
/**
219
* Test if array or string contains expected element/substring
220
* @param expected - Element or substring to find
221
*/
222
toContain(expected: any): boolean;
223
224
/**
225
* Test if object has a size/length property with expected value
226
* @param expected - Expected size/length
227
*/
228
toHaveSize(expected: number): boolean;
229
}
230
```
231
232
**Usage Examples:**
233
234
```javascript
235
// Array containment
236
expect([1, 2, 3]).toContain(2);
237
expect(['apple', 'banana']).toContain('banana');
238
239
// String containment
240
expect('hello world').toContain('world');
241
expect('jasmine testing').toContain('test');
242
243
// Size testing
244
expect([1, 2, 3]).toHaveSize(3);
245
expect('hello').toHaveSize(5);
246
expect(new Set([1, 2, 3])).toHaveSize(3);
247
```
248
249
### Pattern Matching
250
251
Matcher for regular expression and string pattern matching.
252
253
```javascript { .api }
254
interface Expectation {
255
/**
256
* Test if string matches regular expression or contains substring
257
* @param expected - RegExp pattern or string to match
258
*/
259
toMatch(expected: string | RegExp): boolean;
260
}
261
```
262
263
**Usage Examples:**
264
265
```javascript
266
expect('hello world').toMatch(/world/);
267
expect('abc123').toMatch(/\d+/);
268
expect('user@example.com').toMatch(/\S+@\S+\.\S+/);
269
270
// String matching
271
expect('hello world').toMatch('world');
272
expect('jasmine').toMatch('mine');
273
```
274
275
### Exception Matchers
276
277
Matchers for testing function execution and exception handling.
278
279
```javascript { .api }
280
interface Expectation {
281
/**
282
* Test if function throws any exception
283
* @param expected - Optional expected error message or type
284
*/
285
toThrow(expected?: any): boolean;
286
287
/**
288
* Test if function throws a specific error
289
* @param expected - Expected error message, type, or instance
290
*/
291
toThrowError(expected?: string | RegExp | Error | Function): boolean;
292
293
/**
294
* Test if function throws error matching predicate
295
* @param predicate - Function to test the thrown error
296
*/
297
toThrowMatching(predicate: (error: any) => boolean): boolean;
298
}
299
```
300
301
**Usage Examples:**
302
303
```javascript
304
// Test that function throws
305
expect(() => {
306
throw new Error('Something went wrong');
307
}).toThrow();
308
309
// Test specific error message
310
expect(() => {
311
throw new Error('Invalid input');
312
}).toThrowError('Invalid input');
313
314
// Test error type
315
expect(() => {
316
throw new TypeError('Wrong type');
317
}).toThrowError(TypeError);
318
319
// Test with predicate
320
expect(() => {
321
throw new Error('Server error: 500');
322
}).toThrowMatching(error => error.message.includes('500'));
323
```
324
325
### Spy Matchers
326
327
Matchers for testing spy behavior and method calls.
328
329
```javascript { .api }
330
interface Expectation {
331
/** Test if spy was called at least once */
332
toHaveBeenCalled(): boolean;
333
334
/**
335
* Test if spy was called specific number of times
336
* @param expected - Expected call count
337
*/
338
toHaveBeenCalledTimes(expected: number): boolean;
339
340
/**
341
* Test if spy was called with specific arguments
342
* @param ...args - Expected arguments
343
*/
344
toHaveBeenCalledWith(...args: any[]): boolean;
345
346
/**
347
* Test if spy was called exactly once with specific arguments
348
* @param ...args - Expected arguments
349
*/
350
toHaveBeenCalledOnceWith(...args: any[]): boolean;
351
352
/**
353
* Test if spy was called before another spy
354
* @param otherSpy - The other spy to compare against
355
*/
356
toHaveBeenCalledBefore(otherSpy: Spy): boolean;
357
358
/** Test if spy has any interactions (calls or property access) */
359
toHaveSpyInteractions(): boolean;
360
}
361
```
362
363
**Usage Examples:**
364
365
```javascript
366
const spy = jasmine.createSpy('testSpy');
367
const obj = { method: jasmine.createSpy('method') };
368
369
spy('arg1', 'arg2');
370
obj.method(123);
371
372
expect(spy).toHaveBeenCalled();
373
expect(spy).toHaveBeenCalledTimes(1);
374
expect(spy).toHaveBeenCalledWith('arg1', 'arg2');
375
expect(spy).toHaveBeenCalledOnceWith('arg1', 'arg2');
376
377
expect(obj.method).toHaveBeenCalledWith(123);
378
expect(spy).toHaveBeenCalledBefore(obj.method);
379
```
380
381
### DOM Matchers
382
383
Matcher for testing DOM element properties.
384
385
```javascript { .api }
386
interface Expectation {
387
/**
388
* Test if DOM element has specific CSS class
389
* @param className - CSS class name to check
390
*/
391
toHaveClass(className: string): boolean;
392
}
393
```
394
395
**Usage Examples:**
396
397
```javascript
398
const element = document.createElement('div');
399
element.className = 'active selected';
400
401
expect(element).toHaveClass('active');
402
expect(element).toHaveClass('selected');
403
expect(element).not.toHaveClass('disabled');
404
```
405
406
### Utility Matchers
407
408
Special utility matchers for testing and development.
409
410
```javascript { .api }
411
interface Expectation {
412
/** Always fails - useful for testing custom matchers */
413
nothing(): boolean;
414
}
415
```
416
417
### Asynchronous Matchers
418
419
Matchers specifically for testing promise states and async operations.
420
421
```javascript { .api }
422
interface AsyncExpectation {
423
/** Test if promise is in pending state */
424
toBePending(): Promise<boolean>;
425
426
/** Test if promise resolved (fulfilled) */
427
toBeResolved(): Promise<boolean>;
428
429
/** Test if promise was rejected */
430
toBeRejected(): Promise<boolean>;
431
432
/**
433
* Test if promise resolved to specific value
434
* @param expected - Expected resolved value
435
*/
436
toBeResolvedTo(expected: any): Promise<boolean>;
437
438
/**
439
* Test if promise was rejected with specific value
440
* @param expected - Expected rejection value
441
*/
442
toBeRejectedWith(expected: any): Promise<boolean>;
443
444
/**
445
* Test if promise was rejected with specific error
446
* @param expected - Expected error type, message, or instance
447
*/
448
toBeRejectedWithError(expected?: string | RegExp | Error | Function): Promise<boolean>;
449
}
450
```
451
452
**Usage Examples:**
453
454
```javascript
455
// Test promise resolution
456
await expectAsync(Promise.resolve(42)).toBeResolved();
457
await expectAsync(Promise.resolve(42)).toBeResolvedTo(42);
458
459
// Test promise rejection
460
await expectAsync(Promise.reject('error')).toBeRejected();
461
await expectAsync(Promise.reject('error')).toBeRejectedWith('error');
462
463
// Test promise errors
464
await expectAsync(
465
Promise.reject(new TypeError('Wrong type'))
466
).toBeRejectedWithError(TypeError);
467
468
// Test pending promises
469
const pendingPromise = new Promise(() => {}); // never resolves
470
await expectAsync(pendingPromise).toBePending();
471
```
472
473
## Types
474
475
```javascript { .api }
476
interface Expectation {
477
not: Expectation;
478
// All matcher methods return boolean
479
}
480
481
interface AsyncExpectation {
482
not: AsyncExpectation;
483
// All async matcher methods return Promise<boolean>
484
}
485
486
interface ExpectationResult {
487
matcherName: string;
488
message: string;
489
stack: string;
490
passed: boolean;
491
expected?: any;
492
actual?: any;
493
}
494
```