-
Notifications
You must be signed in to change notification settings - Fork 30.5k
/
Copy pathassert.md
608 lines (493 loc) Β· 15.7 KB
1
# Assert
2
3
> Stability: 2 - Stable
4
5
The `assert` module provides a simple set of assertion tests that can be used to
6
test invariants.
7
8
## assert(value[, message])
9
10
11
<!-- YAML
added: v0.5.9
-->
12
13
* `value` {any}
* `message` {any}
14
15
An alias of [`assert.ok()`][].
16
17
## assert.deepEqual(actual, expected[, message])
18
19
<!-- YAML
added: v0.1.21
20
changes:
21
22
23
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/12142
description: Set and Map content is also compared
24
25
26
27
28
29
30
31
32
- version: v6.4.0, v4.7.1
pr-url: https://github.com/nodejs/node/pull/8002
description: Typed array slices are handled correctly now.
- version: v6.1.0, v4.5.0
pr-url: https://github.com/nodejs/node/pull/6432
description: Objects with circular references can be used as inputs now.
- version: v5.10.1, v4.4.3
pr-url: https://github.com/nodejs/node/pull/5910
description: Handle non-`Uint8Array` typed arrays correctly.
33
-->
34
35
36
* `actual` {any}
* `expected` {any}
* `message` {any}
37
38
Tests for deep equality between the `actual` and `expected` parameters.
39
40
41
42
43
44
45
Primitive values are compared with the [Abstract Equality Comparison][]
( `==` ).
Only [enumerable "own" properties][] are considered. The
[`assert.deepEqual()`][] implementation does not test the
[`[[Prototype]]`][prototype-spec] of objects, attached symbols, or
non-enumerable properties β for such checks, consider using
46
[`assert.deepStrictEqual()`][] instead. This can lead to some
47
48
49
potentially surprising results. For example, the following example does not
throw an `AssertionError` because the properties on the [`Error`][] object are
not enumerable:
50
51
52
53
54
```js
// WARNING: This does not throw an AssertionError!
assert.deepEqual(Error('a'), Error('b'));
```
55
56
57
58
An exception is made for [`Map`][] and [`Set`][]. Maps and Sets have their
contained items compared too, as expected.
59
60
61
"Deep" equality means that the enumerable "own" properties of child objects
are evaluated also:
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
```js
const assert = require('assert');
const obj1 = {
a : {
b : 1
}
};
const obj2 = {
a : {
b : 2
}
};
const obj3 = {
a : {
b : 1
}
79
};
80
81
82
const obj4 = Object.create(obj1);
assert.deepEqual(obj1, obj1);
83
// OK, object is equal to itself
84
85
assert.deepEqual(obj1, obj2);
86
87
// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
// values of b are different
88
89
assert.deepEqual(obj1, obj3);
90
// OK, objects are equal
91
92
assert.deepEqual(obj1, obj4);
93
94
// AssertionError: { a: { b: 1 } } deepEqual {}
// Prototypes are ignored
95
```
96
97
98
99
100
If the values are not equal, an `AssertionError` is thrown with a `message`
property set equal to the value of the `message` parameter. If the `message`
parameter is undefined, a default error message is assigned.
101
## assert.deepStrictEqual(actual, expected[, message])
102
103
<!-- YAML
added: v1.2.0
104
changes:
105
106
107
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/12142
description: Set and Map content is also compared
108
109
110
111
112
113
114
115
116
- version: v6.4.0, v4.7.1
pr-url: https://github.com/nodejs/node/pull/8002
description: Typed array slices are handled correctly now.
- version: v6.1.0
pr-url: https://github.com/nodejs/node/pull/6432
description: Objects with circular references can be used as inputs now.
- version: v5.10.1, v4.4.3
pr-url: https://github.com/nodejs/node/pull/5910
description: Handle non-`Uint8Array` typed arrays correctly.
117
-->
118
119
120
* `actual` {any}
* `expected` {any}
* `message` {any}
121
122
Generally identical to `assert.deepEqual()` with three exceptions:
123
124
1. Primitive values are compared using the [Strict Equality Comparison][]
125
126
( `===` ). Set values and Map keys are compared using the [SameValueZero][]
comparison. (Which means they are free of the [caveats][]).
127
128
2. [`[[Prototype]]`][prototype-spec] of objects are compared using
the [Strict Equality Comparison][] too.
129
3. [Type tags][Object.prototype.toString()] of objects should be the same.
130
131
132
```js
const assert = require('assert');
133
134
assert.deepEqual({a: 1}, {a: '1'});
135
// OK, because 1 == '1'
136
137
assert.deepStrictEqual({a: 1}, {a: '1'});
138
139
// AssertionError: { a: 1 } deepStrictEqual { a: '1' }
// because 1 !== '1' using strict equality
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
// The following objects don't have own properties
const date = new Date();
const object = {};
const fakeDate = {};
Object.setPrototypeOf(fakeDate, Date.prototype);
assert.deepEqual(object, fakeDate);
// OK, doesn't check [[Prototype]]
assert.deepStrictEqual(object, fakeDate);
// AssertionError: {} deepStrictEqual Date {}
// Different [[Prototype]]
assert.deepEqual(date, fakeDate);
// OK, doesn't check type tags
assert.deepStrictEqual(date, fakeDate);
// AssertionError: 2017-03-11T14:25:31.849Z deepStrictEqual Date {}
// Different type tags
159
```
160
161
162
163
If the values are not equal, an `AssertionError` is thrown with a `message`
property set equal to the value of the `message` parameter. If the `message`
parameter is undefined, a default error message is assigned.
164
165
## assert.doesNotThrow(block[, error][, message])
166
167
<!-- YAML
added: v0.1.21
168
169
170
171
172
173
174
changes:
- version: v5.11.0, v4.4.5
pr-url: https://github.com/nodejs/node/pull/2407
description: The `message` parameter is respected now.
- version: v4.2.0
pr-url: https://github.com/nodejs/node/pull/3276
description: The `error` parameter can now be an arrow function.
175
-->
176
177
178
* `block` {Function}
* `error` {RegExp|Function}
* `message` {any}
179
180
181
182
183
184
185
186
187
188
189
Asserts that the function `block` does not throw an error. See
[`assert.throws()`][] for more details.
When `assert.doesNotThrow()` is called, it will immediately call the `block`
function.
If an error is thrown and it is the same type as that specified by the `error`
parameter, then an `AssertionError` is thrown. If the error is of a different
type, or if the `error` parameter is undefined, the error is propagated back
to the caller.
190
191
192
The following, for instance, will throw the [`TypeError`][] because there is no
matching error type in the assertion:
193
194
195
```js
assert.doesNotThrow(
196
() => {
197
198
199
200
201
throw new TypeError('Wrong value');
},
SyntaxError
);
```
202
203
204
However, the following will result in an `AssertionError` with the message
'Got unwanted exception (TypeError)..':
205
206
207
```js
assert.doesNotThrow(
208
() => {
209
210
211
212
213
throw new TypeError('Wrong value');
},
TypeError
);
```
214
215
216
217
218
If an `AssertionError` is thrown and a value is provided for the `message`
parameter, the value of `message` will be appended to the `AssertionError`
message:
219
220
```js
assert.doesNotThrow(
221
() => {
222
223
224
225
226
227
228
throw new TypeError('Wrong value');
},
TypeError,
'Whoops'
);
// Throws: AssertionError: Got unwanted exception (TypeError). Whoops
```
229
230
## assert.equal(actual, expected[, message])
231
232
233
<!-- YAML
added: v0.1.21
-->
234
235
236
* `actual` {any}
* `expected` {any}
* `message` {any}
237
238
Tests shallow, coercive equality between the `actual` and `expected` parameters
239
using the [Abstract Equality Comparison][] ( `==` ).
240
241
242
```js
const assert = require('assert');
243
244
assert.equal(1, 1);
245
// OK, 1 == 1
246
assert.equal(1, '1');
247
// OK, 1 == '1'
248
249
assert.equal(1, 2);
250
// AssertionError: 1 == 2
251
assert.equal({a: {b: 1}}, {a: {b: 1}});
252
//AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
253
```
254
255
256
257
If the values are not equal, an `AssertionError` is thrown with a `message`
property set equal to the value of the `message` parameter. If the `message`
parameter is undefined, a default error message is assigned.
258
259
## assert.fail(message)
260
## assert.fail(actual, expected, message, operator)
261
262
263
<!-- YAML
added: v0.1.21
-->
264
265
266
* `actual` {any}
* `expected` {any}
* `message` {any}
267
* `operator` {string} (default: '!=')
268
269
270
271
272
Throws an `AssertionError`. If `message` is falsy, the error message is set as
the values of `actual` and `expected` separated by the provided `operator`.
Otherwise, the error message is the value of `message`.
273
274
```js
const assert = require('assert');
275
276
assert.fail(1, 2, undefined, '>');
277
// AssertionError: 1 > 2
278
279
assert.fail(1, 2, 'whoops', '>');
280
// AssertionError: whoops
281
282
283
284
285
286
assert.fail('boom');
// AssertionError: boom
assert.fail('a', 'b');
// AssertionError: 'a' != 'b'
287
```
288
289
## assert.ifError(value)
290
291
292
<!-- YAML
added: v0.1.97
-->
293
* `value` {any}
294
295
296
297
Throws `value` if `value` is truthy. This is useful when testing the `error`
argument in callbacks.
298
299
```js
const assert = require('assert');
300
301
302
303
304
305
306
307
308
assert.ifError(0);
// OK
assert.ifError(1);
// Throws 1
assert.ifError('error');
// Throws 'error'
assert.ifError(new Error());
// Throws Error
309
```
310
311
## assert.notDeepEqual(actual, expected[, message])
312
313
314
<!-- YAML
added: v0.1.21
-->
315
316
317
* `actual` {any}
* `expected` {any}
* `message` {any}
318
319
Tests for any deep inequality. Opposite of [`assert.deepEqual()`][].
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
```js
const assert = require('assert');
const obj1 = {
a : {
b : 1
}
};
const obj2 = {
a : {
b : 2
}
};
const obj3 = {
a : {
b : 1
}
338
};
339
340
const obj4 = Object.create(obj1);
341
assert.notDeepEqual(obj1, obj1);
342
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
343
344
assert.notDeepEqual(obj1, obj2);
345
// OK, obj1 and obj2 are not deeply equal
346
347
assert.notDeepEqual(obj1, obj3);
348
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
349
350
assert.notDeepEqual(obj1, obj4);
351
// OK, obj1 and obj2 are not deeply equal
352
```
353
354
355
356
357
If the values are deeply equal, an `AssertionError` is thrown with a `message`
property set equal to the value of the `message` parameter. If the `message`
parameter is undefined, a default error message is assigned.
358
## assert.notDeepStrictEqual(actual, expected[, message])
359
360
361
<!-- YAML
added: v1.2.0
-->
362
363
364
* `actual` {any}
* `expected` {any}
* `message` {any}
365
366
Tests for deep strict inequality. Opposite of [`assert.deepStrictEqual()`][].
367
368
369
```js
const assert = require('assert');
370
371
assert.notDeepEqual({a:1}, {a:'1'});
372
// AssertionError: { a: 1 } notDeepEqual { a: '1' }
373
374
assert.notDeepStrictEqual({a:1}, {a:'1'});
375
// OK
376
```
377
378
379
380
If the values are deeply and strictly equal, an `AssertionError` is thrown
with a `message` property set equal to the value of the `message` parameter. If
the `message` parameter is undefined, a default error message is assigned.
381
382
## assert.notEqual(actual, expected[, message])
383
384
385
<!-- YAML
added: v0.1.21
-->
386
387
388
* `actual` {any}
* `expected` {any}
* `message` {any}
389
390
Tests shallow, coercive inequality with the [Abstract Equality Comparison][]
391
( `!=` ).
392
393
394
```js
const assert = require('assert');
395
396
assert.notEqual(1, 2);
397
// OK
398
399
assert.notEqual(1, 1);
400
// AssertionError: 1 != 1
401
402
assert.notEqual(1, '1');
403
// AssertionError: 1 != '1'
404
```
405
406
407
408
409
If the values are equal, an `AssertionError` is thrown with a `message`
property set equal to the value of the `message` parameter. If the `message`
parameter is undefined, a default error message is assigned.
410
## assert.notStrictEqual(actual, expected[, message])
411
412
413
<!-- YAML
added: v0.1.21
-->
414
415
416
* `actual` {any}
* `expected` {any}
* `message` {any}
417
418
Tests strict inequality as determined by the [Strict Equality Comparison][]
419
( `!==` ).
420
421
422
```js
const assert = require('assert');
423
424
assert.notStrictEqual(1, 2);
425
// OK
426
427
assert.notStrictEqual(1, 1);
428
// AssertionError: 1 !== 1
429
430
assert.notStrictEqual(1, '1');
431
// OK
432
```
433
434
435
436
437
If the values are strictly equal, an `AssertionError` is thrown with a
`message` property set equal to the value of the `message` parameter. If the
`message` parameter is undefined, a default error message is assigned.
438
## assert.ok(value[, message])
439
440
441
<!-- YAML
added: v0.1.21
-->
442
443
* `value` {any}
* `message` {any}
444
445
446
447
448
449
450
451
452
453
454
Tests if `value` is truthy. It is equivalent to
`assert.equal(!!value, true, message)`.
If `value` is not truthy, an `AssertionError` is thrown with a `message`
property set equal to the value of the `message` parameter. If the `message`
parameter is `undefined`, a default error message is assigned.
```js
const assert = require('assert');
455
456
457
458
assert.ok(true);
// OK
assert.ok(1);
// OK
459
assert.ok(false);
460
// throws "AssertionError: false == true"
461
assert.ok(0);
462
// throws "AssertionError: 0 == true"
463
assert.ok(false, 'it\'s false');
464
// throws "AssertionError: it's false"
465
466
```
467
## assert.strictEqual(actual, expected[, message])
468
469
470
<!-- YAML
added: v0.1.21
-->
471
472
473
* `actual` {any}
* `expected` {any}
* `message` {any}
474
475
476
Tests strict equality as determined by the [Strict Equality Comparison][]
( `===` ).
477
478
479
```js
const assert = require('assert');
480
481
assert.strictEqual(1, 2);
482
// AssertionError: 1 === 2
483
484
assert.strictEqual(1, 1);
485
// OK
486
487
assert.strictEqual(1, '1');
488
// AssertionError: 1 === '1'
489
```
490
491
492
493
494
If the values are not strictly equal, an `AssertionError` is thrown with a
`message` property set equal to the value of the `message` parameter. If the
`message` parameter is undefined, a default error message is assigned.
495
## assert.throws(block[, error][, message])
496
497
<!-- YAML
added: v0.1.21
498
499
500
501
changes:
- version: v4.2.0
pr-url: https://github.com/nodejs/node/pull/3276
description: The `error` parameter can now be an arrow function.
502
-->
503
504
505
* `block` {Function}
* `error` {RegExp|Function}
* `message` {any}
506
507
508
509
510
511
512
513
Expects the function `block` to throw an error.
If specified, `error` can be a constructor, [`RegExp`][], or validation
function.
If specified, `message` will be the message provided by the `AssertionError` if
the block fails to throw.
514
515
516
Validate instanceof using constructor:
517
518
```js
assert.throws(
519
() => {
520
521
522
523
524
throw new Error('Wrong value');
},
Error
);
```
525
526
Validate error message using [`RegExp`][]:
527
528
529
```js
assert.throws(
530
() => {
531
532
533
534
535
throw new Error('Wrong value');
},
/value/
);
```
536
537
538
Custom error validation:
539
540
```js
assert.throws(
541
() => {
542
543
544
545
546
547
548
549
550
551
throw new Error('Wrong value');
},
function(err) {
if ( (err instanceof Error) && /value/.test(err) ) {
return true;
}
},
'unexpected error'
);
```
552
553
554
555
556
557
558
559
560
561
562
563
564
Note that `error` can not be a string. If a string is provided as the second
argument, then `error` is assumed to be omitted and the string will be used for
`message` instead. This can lead to easy-to-miss mistakes:
```js
// THIS IS A MISTAKE! DO NOT DO THIS!
assert.throws(myFunction, 'missing foo', 'did not throw with expected message');
// Do this instead.
assert.throws(myFunction, /missing foo/, 'did not throw with expected message');
```
565
566
567
568
569
570
571
572
573
574
575
576
577
578
## Caveats
For the following cases, consider using ES2015 [`Object.is()`][],
which uses the [SameValueZero][] comparison.
```js
const a = 0;
const b = -a;
assert.notStrictEqual(a, b);
// AssertionError: 0 !== -0
// Strict Equality Comparison doesn't distinguish between -0 and +0...
assert(!Object.is(a, b));
// but Object.is() does!
579
580
const str1 = 'foo';
const str2 = 'foo';
581
582
583
584
585
586
587
588
589
590
assert.strictEqual(str1 / 1, str2 / 1);
// AssertionError: NaN === NaN
// Strict Equality Comparison can't be used to check NaN...
assert(Object.is(str1 / 1, str2 / 1));
// but Object.is() can!
```
For more information, see
[MDN's guide on equality comparisons and sameness][mdn-equality-guide].
591
592
[`assert.deepEqual()`]: #assert_assert_deepequal_actual_expected_message
[`assert.deepStrictEqual()`]: #assert_assert_deepstrictequal_actual_expected_message
593
[`assert.ok()`]: #assert_assert_ok_value_message
594
595
[`assert.throws()`]: #assert_assert_throws_block_error_message
[`Error`]: errors.html#errors_class_error
596
[caveats]: #assert_caveats
597
[`RegExp`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
598
[`TypeError`]: errors.html#errors_class_typeerror
599
600
[Abstract Equality Comparison]: https://tc39.github.io/ecma262/#sec-abstract-equality-comparison
[Strict Equality Comparison]: https://tc39.github.io/ecma262/#sec-strict-equality-comparison
601
602
[`Map`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map
[`Set`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Set
603
604
605
606
[`Object.is()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
[SameValueZero]: https://tc39.github.io/ecma262/#sec-samevaluezero
[prototype-spec]: https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots
[mdn-equality-guide]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
607
608
[enumerable "own" properties]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties
[Object.prototype.toString()]: https://tc39.github.io/ecma262/#sec-object.prototype.tostring