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