-
-
Notifications
You must be signed in to change notification settings - Fork 35.5k
Expand file tree
/
Copy pathassert.md
More file actions
643 lines (523 loc) Β· 17.1 KB
/
assert.md
File metadata and controls
643 lines (523 loc) Β· 17.1 KB
Edit and raw actions
OlderNewer
Β
1
# Assert
2
3
<!--introduced_in=v0.10.0-->
4
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
<!-- YAML
12
added: v0.5.9
13
-->
14
* `value` {any}
15
* `message` {any}
16
17
An alias of [`assert.ok()`][].
18
19
## assert.deepEqual(actual, expected[, message])
20
<!-- YAML
21
added: v0.1.21
22
changes:
23
- version: v8.0.0
24
pr-url: https://github.com/nodejs/node/pull/12142
25
description: Set and Map content is also compared
26
- version: v6.4.0, v4.7.1
27
pr-url: https://github.com/nodejs/node/pull/8002
28
description: Typed array slices are handled correctly now.
29
- version: v6.1.0, v4.5.0
30
pr-url: https://github.com/nodejs/node/pull/6432
31
description: Objects with circular references can be used as inputs now.
32
- version: v5.10.1, v4.4.3
33
pr-url: https://github.com/nodejs/node/pull/5910
34
description: Handle non-`Uint8Array` typed arrays correctly.
35
-->
36
* `actual` {any}
37
* `expected` {any}
38
* `message` {any}
39
40
Tests for deep equality between the `actual` and `expected` parameters.
41
Primitive values are compared with the [Abstract Equality Comparison][]
42
( `==` ).
43
44
Only [enumerable "own" properties][] are considered. The
45
[`assert.deepEqual()`][] implementation does not test the
46
[`[[Prototype]]`][prototype-spec] of objects, attached symbols, or
47
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
```js
54
// WARNING: This does not throw an AssertionError!
55
assert.deepEqual(/a/gi, new Date());
56
```
57
58
An exception is made for [`Map`][] and [`Set`][]. Maps and Sets have their
59
contained items compared too, as expected.
60
61
"Deep" equality means that the enumerable "own" properties of child objects
62
are evaluated also:
63
64
```js
65
const assert = require('assert');
66
67
const obj1 = {
68
a: {
69
b: 1
70
}
71
};
72
const obj2 = {
73
a: {
74
b: 2
75
}
76
};
77
const obj3 = {
78
a: {
79
b: 1
80
}
81
};
82
const obj4 = Object.create(obj1);
83
84
assert.deepEqual(obj1, obj1);
85
// OK, object is equal to itself
86
87
assert.deepEqual(obj1, obj2);
88
// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
89
// values of b are different
90
91
assert.deepEqual(obj1, obj3);
92
// OK, objects are equal
93
94
assert.deepEqual(obj1, obj4);
95
// AssertionError: { a: { b: 1 } } deepEqual {}
96
// Prototypes are ignored
97
```
98
99
If the values are not equal, an `AssertionError` is thrown with a `message`
100
property set equal to the value of the `message` parameter. If the `message`
101
parameter is undefined, a default error message is assigned.
102
103
## assert.deepStrictEqual(actual, expected[, message])
104
<!-- YAML
105
added: v1.2.0
106
changes:
107
- version: v8.5.0
108
pr-url: https://github.com/nodejs/node/pull/12142
109
description: Error names and messages are now properly compared
110
- version: v8.0.0
111
pr-url: https://github.com/nodejs/node/pull/12142
112
description: Set and Map content is also compared
113
- version: v6.4.0, v4.7.1
114
pr-url: https://github.com/nodejs/node/pull/8002
115
description: Typed array slices are handled correctly now.
116
- version: v6.1.0
117
pr-url: https://github.com/nodejs/node/pull/6432
118
description: Objects with circular references can be used as inputs now.
119
- version: v5.10.1, v4.4.3
120
pr-url: https://github.com/nodejs/node/pull/5910
121
description: Handle non-`Uint8Array` typed arrays correctly.
122
-->
123
* `actual` {any}
124
* `expected` {any}
125
* `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
( `===` ). Set values and Map keys are compared using the [SameValueZero][]
131
comparison. (Which means they are free of the [caveats][]).
132
2. [`[[Prototype]]`][prototype-spec] of objects are compared using
133
the [Strict Equality Comparison][] too.
134
3. [Type tags][Object.prototype.toString()] of objects should be the same.
135
136
```js
137
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
// AssertionError: { a: 1 } deepStrictEqual { a: '1' }
144
// because 1 !== '1' using strict equality
145
146
// The following objects don't have own properties
147
const date = new Date();
148
const object = {};
149
const fakeDate = {};
150
151
Object.setPrototypeOf(fakeDate, Date.prototype);
152
153
assert.deepEqual(object, fakeDate);
154
// OK, doesn't check [[Prototype]]
155
assert.deepStrictEqual(object, fakeDate);
156
// AssertionError: {} deepStrictEqual Date {}
157
// Different [[Prototype]]
158
159
assert.deepEqual(date, fakeDate);
160
// OK, doesn't check type tags
161
assert.deepStrictEqual(date, fakeDate);
162
// AssertionError: 2017-03-11T14:25:31.849Z deepStrictEqual Date {}
163
// Different type tags
164
```
165
166
If the values are not equal, an `AssertionError` is thrown with a `message`
167
property set equal to the value of the `message` parameter. If the `message`
168
parameter is undefined, a default error message is assigned.
169
170
## assert.doesNotThrow(block[, error][, message])
171
<!-- YAML
172
added: v0.1.21
173
changes:
174
- version: v5.11.0, v4.4.5
175
pr-url: https://github.com/nodejs/node/pull/2407
176
description: The `message` parameter is respected now.
177
- version: v4.2.0
178
pr-url: https://github.com/nodejs/node/pull/3276
179
description: The `error` parameter can now be an arrow function.
180
-->
181
* `block` {Function}
182
* `error` {RegExp|Function}
183
* `message` {any}
184
185
Asserts that the function `block` does not throw an error. See
186
[`assert.throws()`][] for more details.
187
188
When `assert.doesNotThrow()` is called, it will immediately call the `block`
189
function.
190
191
If an error is thrown and it is the same type as that specified by the `error`
192
parameter, then an `AssertionError` is thrown. If the error is of a different
193
type, or if the `error` parameter is undefined, the error is propagated back
194
to the caller.
195
196
The following, for instance, will throw the [`TypeError`][] because there is no
197
matching error type in the assertion:
198
199
```js
200
assert.doesNotThrow(
201
() => {
202
throw new TypeError('Wrong value');
203
},
204
SyntaxError
205
);
206
```
207
208
However, the following will result in an `AssertionError` with the message
209
'Got unwanted exception (TypeError)..':
210
211
```js
212
assert.doesNotThrow(
213
() => {
214
throw new TypeError('Wrong value');
215
},
216
TypeError
217
);
218
```
219
220
If an `AssertionError` is thrown and a value is provided for the `message`
221
parameter, the value of `message` will be appended to the `AssertionError`
222
message:
223
224
```js
225
assert.doesNotThrow(
226
() => {
227
throw new TypeError('Wrong value');
228
},
229
TypeError,
230
'Whoops'
231
);
232
// Throws: AssertionError: Got unwanted exception (TypeError). Whoops
233
```
234
235
## assert.equal(actual, expected[, message])
236
<!-- YAML
237
added: v0.1.21
238
-->
239
* `actual` {any}
240
* `expected` {any}
241
* `message` {any}
242
243
Tests shallow, coercive equality between the `actual` and `expected` parameters
244
using the [Abstract Equality Comparison][] ( `==` ).
245
246
```js
247
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
If the values are not equal, an `AssertionError` is thrown with a `message`
261
property set equal to the value of the `message` parameter. If the `message`
262
parameter is undefined, a default error message is assigned.
263
264
## assert.fail(message)
265
## assert.fail(actual, expected[, message[, operator[, stackStartFunction]]])
266
<!-- YAML
267
added: v0.1.21
268
-->
269
* `actual` {any}
270
* `expected` {any}
271
* `message` {any}
272
* `operator` {string} (default: '!=')
273
* `stackStartFunction` {function} (default: `assert.fail`)
274
275
Throws an `AssertionError`. If `message` is falsy, the error message is set as
276
the values of `actual` and `expected` separated by the provided `operator`.
277
If just the two `actual` and `expected` arguments are provided, `operator` will
278
default to `'!='`. If `message` is provided only it will be used as the error
279
message, the other arguments will be stored as properties on the thrown object.
280
If `stackStartFunction` is provided, all stack frames above that function will
281
be removed from stacktrace (see [`Error.captureStackTrace`]).
282
283
```js
284
const assert = require('assert');
285
286
assert.fail(1, 2, undefined, '>');
287
// AssertionError [ERR_ASSERTION]: 1 > 2
288
289
assert.fail(1, 2, 'fail');
290
// AssertionError [ERR_ASSERTION]: fail
291
292
assert.fail(1, 2, 'whoops', '>');
293
// AssertionError [ERR_ASSERTION]: whoops
294
```
295
296
*Note*: Is the last two cases `actual`, `expected`, and `operator` have no
297
influence on the error message.
298
299
```js
300
assert.fail();
301
// AssertionError [ERR_ASSERTION]: Failed
302
303
assert.fail('boom');
304
// AssertionError [ERR_ASSERTION]: boom
305
306
assert.fail('a', 'b');
307
// AssertionError [ERR_ASSERTION]: 'a' != 'b'
308
```
309
310
Example use of `stackStartFunction` for truncating the exception's stacktrace:
311
```js
312
function suppressFrame() {
313
assert.fail('a', 'b', undefined, '!==', suppressFrame);
314
}
315
suppressFrame();
316
// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
317
// at repl:1:1
318
// at ContextifyScript.Script.runInThisContext (vm.js:44:33)
319
// ...
320
```
321
322
## assert.ifError(value)
323
<!-- YAML
324
added: v0.1.97
325
-->
326
* `value` {any}
327
328
Throws `value` if `value` is truthy. This is useful when testing the `error`
329
argument in callbacks.
330
331
```js
332
const assert = require('assert');
333
334
assert.ifError(0);
335
// OK
336
assert.ifError(1);
337
// Throws 1
338
assert.ifError('error');
339
// Throws 'error'
340
assert.ifError(new Error());
341
// Throws Error
342
```
343
344
## assert.notDeepEqual(actual, expected[, message])
345
<!-- YAML
346
added: v0.1.21
347
-->
348
* `actual` {any}
349
* `expected` {any}
350
* `message` {any}
351
352
Tests for any deep inequality. Opposite of [`assert.deepEqual()`][].
353
354
```js
355
const assert = require('assert');
356
357
const obj1 = {
358
a: {
359
b: 1
360
}
361
};
362
const obj2 = {
363
a: {
364
b: 2
365
}
366
};
367
const obj3 = {
368
a: {
369
b: 1
370
}
371
};
372
const obj4 = Object.create(obj1);
373
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
If the values are deeply equal, an `AssertionError` is thrown with a `message`
388
property set equal to the value of the `message` parameter. If the `message`
389
parameter is undefined, a default error message is assigned.
390
391
## assert.notDeepStrictEqual(actual, expected[, message])
392
<!-- YAML
393
added: v1.2.0
394
-->
395
* `actual` {any}
396
* `expected` {any}
397
* `message` {any}
398
399
Tests for deep strict inequality. Opposite of [`assert.deepStrictEqual()`][].
400
401
```js
402
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
If the values are deeply and strictly equal, an `AssertionError` is thrown
412
with a `message` property set equal to the value of the `message` parameter. If
413
the `message` parameter is undefined, a default error message is assigned.
414
415
## assert.notEqual(actual, expected[, message])
416
<!-- YAML
417
added: v0.1.21
418
-->
419
* `actual` {any}
420
* `expected` {any}
421
* `message` {any}
422
423
Tests shallow, coercive inequality with the [Abstract Equality Comparison][]
424
( `!=` ).
425
426
```js
427
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
If the values are equal, an `AssertionError` is thrown with a `message`
440
property set equal to the value of the `message` parameter. If the `message`
441
parameter is undefined, a default error message is assigned.
442
443
## assert.notStrictEqual(actual, expected[, message])
444
<!-- YAML
445
added: v0.1.21
446
-->
447
* `actual` {any}
448
* `expected` {any}
449
* `message` {any}
450
451
Tests strict inequality as determined by the [Strict Equality Comparison][]
452
( `!==` ).
453
454
```js
455
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
If the values are strictly equal, an `AssertionError` is thrown with a
468
`message` property set equal to the value of the `message` parameter. If the
469
`message` parameter is undefined, a default error message is assigned.
470
471
## assert.ok(value[, message])
472
<!-- YAML
473
added: v0.1.21
474
-->
475
* `value` {any}
476
* `message` {any}
477
478
Tests if `value` is truthy. It is equivalent to
479
`assert.equal(!!value, true, message)`.
480
481
If `value` is not truthy, an `AssertionError` is thrown with a `message`
482
property set equal to the value of the `message` parameter. If the `message`
483
parameter is `undefined`, a default error message is assigned.
484
485
```js
486
const assert = require('assert');
487
488
assert.ok(true);
489
// OK
490
assert.ok(1);
491
// 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
<!-- YAML
502
added: v0.1.21
503
-->
504
* `actual` {any}
505
* `expected` {any}
506
* `message` {any}
507
508
Tests strict equality as determined by the [Strict Equality Comparison][]
509
( `===` ).
510
511
```js
512
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
If the values are not strictly equal, an `AssertionError` is thrown with a
525
`message` property set equal to the value of the `message` parameter. If the
526
`message` parameter is undefined, a default error message is assigned.
527
528
## assert.throws(block[, error][, message])
529
<!-- YAML
530
added: v0.1.21
531
changes:
532
- version: v4.2.0
533
pr-url: https://github.com/nodejs/node/pull/3276
534
description: The `error` parameter can now be an arrow function.
535
-->
536
* `block` {Function}
537
* `error` {RegExp|Function}
538
* `message` {any}
539
540
Expects the function `block` to throw an error.
541
542
If specified, `error` can be a constructor, [`RegExp`][], or validation
543
function.
544
545
If specified, `message` will be the message provided by the `AssertionError` if
546
the block fails to throw.
547
548
Validate instanceof using constructor:
549
550
```js
551
assert.throws(
552
() => {
553
throw new Error('Wrong value');
554
},
555
Error
556
);
557
```
558
559
Validate error message using [`RegExp`][]:
560
561
```js
562
assert.throws(
563
() => {
564
throw new Error('Wrong value');
565
},
566
/value/
567
);
568
```
569
570
Custom error validation:
571
572
```js
573
assert.throws(
574
() => {
575
throw new Error('Wrong value');
576
},
577
function(err) {
578
if ((err instanceof Error) && /value/.test(err)) {
579
return true;
580
}
581
},
582
'unexpected error'
583
);
584
```
585
586
Note that `error` can not be a string. If a string is provided as the second
587
argument, then `error` is assumed to be omitted and the string will be used for
588
`message` instead. This can lead to easy-to-miss mistakes:
589
590
<!-- eslint-disable no-restricted-syntax -->
591
```js
592
// THIS IS A MISTAKE! DO NOT DO THIS!
593
assert.throws(myFunction, 'missing foo', 'did not throw with expected message');
594
595
// Do this instead.
596
assert.throws(myFunction, /missing foo/, 'did not throw with expected message');
597
```
598
599
## Caveats
600
601
For the following cases, consider using ES2015 [`Object.is()`][],
602
which uses the [SameValueZero][] comparison.
603
604
```js
605
const a = 0;
606
const b = -a;
607
assert.notStrictEqual(a, b);
608
// AssertionError: 0 !== -0
609
// Strict Equality Comparison doesn't distinguish between -0 and +0...
610
assert(!Object.is(a, b));
611
// but Object.is() does!
612
613
const str1 = 'foo';
614
const str2 = 'foo';
615
assert.strictEqual(str1 / 1, str2 / 1);
616
// AssertionError: NaN === NaN
617
// Strict Equality Comparison can't be used to check NaN...
618
assert(Object.is(str1 / 1, str2 / 1));
619
// but Object.is() can!
620
```
621
622
For more information, see
623
[MDN's guide on equality comparisons and sameness][mdn-equality-guide].
624
625
[`Error`]: errors.html#errors_class_error
626
[`Error.captureStackTrace`]: errors.html#errors_error_capturestacktrace_targetobject_constructoropt
627
[`Map`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map
628
[`Object.is()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
629
[`RegExp`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
630
[`Set`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Set
631
[`TypeError`]: errors.html#errors_class_typeerror
632
[`assert.deepEqual()`]: #assert_assert_deepequal_actual_expected_message
633
[`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
[Strict Equality Comparison]: https://tc39.github.io/ecma262/#sec-strict-equality-comparison
640
[caveats]: #assert_caveats
641
[enumerable "own" properties]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties
642
[mdn-equality-guide]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
643
[prototype-spec]: https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots