• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Assert
2
3<!--introduced_in=v0.1.21-->
4
5> Stability: 2 - Stable
6
7<!-- source_link=lib/assert.js -->
8
9The `node:assert` module provides a set of assertion functions for verifying
10invariants.
11
12## Strict assertion mode
13
14<!-- YAML
15added: v9.9.0
16changes:
17  - version: v15.0.0
18    pr-url: https://github.com/nodejs/node/pull/34001
19    description: Exposed as `require('node:assert/strict')`.
20  - version:
21      - v13.9.0
22      - v12.16.2
23    pr-url: https://github.com/nodejs/node/pull/31635
24    description: Changed "strict mode" to "strict assertion mode" and "legacy
25                 mode" to "legacy assertion mode" to avoid confusion with the
26                 more usual meaning of "strict mode".
27  - version: v9.9.0
28    pr-url: https://github.com/nodejs/node/pull/17615
29    description: Added error diffs to the strict assertion mode.
30  - version: v9.9.0
31    pr-url: https://github.com/nodejs/node/pull/17002
32    description: Added strict assertion mode to the assert module.
33-->
34
35In strict assertion mode, non-strict methods behave like their corresponding
36strict methods. For example, [`assert.deepEqual()`][] will behave like
37[`assert.deepStrictEqual()`][].
38
39In strict assertion mode, error messages for objects display a diff. In legacy
40assertion mode, error messages for objects display the objects, often truncated.
41
42To use strict assertion mode:
43
44```mjs
45import { strict as assert } from 'node:assert';
46```
47
48```cjs
49const assert = require('node:assert').strict;
50```
51
52```mjs
53import assert from 'node:assert/strict';
54```
55
56```cjs
57const assert = require('node:assert/strict');
58```
59
60Example error diff:
61
62```mjs
63import { strict as assert } from 'node:assert';
64
65assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
66// AssertionError: Expected inputs to be strictly deep-equal:
67// + actual - expected ... Lines skipped
68//
69//   [
70//     [
71// ...
72//       2,
73// +     3
74// -     '3'
75//     ],
76// ...
77//     5
78//   ]
79```
80
81```cjs
82const assert = require('node:assert/strict');
83
84assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
85// AssertionError: Expected inputs to be strictly deep-equal:
86// + actual - expected ... Lines skipped
87//
88//   [
89//     [
90// ...
91//       2,
92// +     3
93// -     '3'
94//     ],
95// ...
96//     5
97//   ]
98```
99
100To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS`
101environment variables. This will also deactivate the colors in the REPL. For
102more on color support in terminal environments, read the tty
103[`getColorDepth()`][] documentation.
104
105## Legacy assertion mode
106
107Legacy assertion mode uses the [`==` operator][] in:
108
109* [`assert.deepEqual()`][]
110* [`assert.equal()`][]
111* [`assert.notDeepEqual()`][]
112* [`assert.notEqual()`][]
113
114To use legacy assertion mode:
115
116```mjs
117import assert from 'node:assert';
118```
119
120```cjs
121const assert = require('node:assert');
122```
123
124Legacy assertion mode may have surprising results, especially when using
125[`assert.deepEqual()`][]:
126
127```cjs
128// WARNING: This does not throw an AssertionError in legacy assertion mode!
129assert.deepEqual(/a/gi, new Date());
130```
131
132## Class: assert.AssertionError
133
134* Extends: {errors.Error}
135
136Indicates the failure of an assertion. All errors thrown by the `node:assert`
137module will be instances of the `AssertionError` class.
138
139### `new assert.AssertionError(options)`
140
141<!-- YAML
142added: v0.1.21
143-->
144
145* `options` {Object}
146  * `message` {string} If provided, the error message is set to this value.
147  * `actual` {any} The `actual` property on the error instance.
148  * `expected` {any} The `expected` property on the error instance.
149  * `operator` {string} The `operator` property on the error instance.
150  * `stackStartFn` {Function} If provided, the generated stack trace omits
151    frames before this function.
152
153A subclass of `Error` that indicates the failure of an assertion.
154
155All instances contain the built-in `Error` properties (`message` and `name`)
156and:
157
158* `actual` {any} Set to the `actual` argument for methods such as
159  [`assert.strictEqual()`][].
160* `expected` {any} Set to the `expected` value for methods such as
161  [`assert.strictEqual()`][].
162* `generatedMessage` {boolean} Indicates if the message was auto-generated
163  (`true`) or not.
164* `code` {string} Value is always `ERR_ASSERTION` to show that the error is an
165  assertion error.
166* `operator` {string} Set to the passed in operator value.
167
168```mjs
169import assert from 'node:assert';
170
171// Generate an AssertionError to compare the error message later:
172const { message } = new assert.AssertionError({
173  actual: 1,
174  expected: 2,
175  operator: 'strictEqual',
176});
177
178// Verify error output:
179try {
180  assert.strictEqual(1, 2);
181} catch (err) {
182  assert(err instanceof assert.AssertionError);
183  assert.strictEqual(err.message, message);
184  assert.strictEqual(err.name, 'AssertionError');
185  assert.strictEqual(err.actual, 1);
186  assert.strictEqual(err.expected, 2);
187  assert.strictEqual(err.code, 'ERR_ASSERTION');
188  assert.strictEqual(err.operator, 'strictEqual');
189  assert.strictEqual(err.generatedMessage, true);
190}
191```
192
193```cjs
194const assert = require('node:assert');
195
196// Generate an AssertionError to compare the error message later:
197const { message } = new assert.AssertionError({
198  actual: 1,
199  expected: 2,
200  operator: 'strictEqual',
201});
202
203// Verify error output:
204try {
205  assert.strictEqual(1, 2);
206} catch (err) {
207  assert(err instanceof assert.AssertionError);
208  assert.strictEqual(err.message, message);
209  assert.strictEqual(err.name, 'AssertionError');
210  assert.strictEqual(err.actual, 1);
211  assert.strictEqual(err.expected, 2);
212  assert.strictEqual(err.code, 'ERR_ASSERTION');
213  assert.strictEqual(err.operator, 'strictEqual');
214  assert.strictEqual(err.generatedMessage, true);
215}
216```
217
218## Class: `assert.CallTracker`
219
220<!-- YAML
221added:
222  - v14.2.0
223  - v12.19.0
224-->
225
226> Stability: 1 - Experimental
227
228This feature is currently experimental and behavior might still change.
229
230### `new assert.CallTracker()`
231
232<!-- YAML
233added:
234  - v14.2.0
235  - v12.19.0
236-->
237
238Creates a new [`CallTracker`][] object which can be used to track if functions
239were called a specific number of times. The `tracker.verify()` must be called
240for the verification to take place. The usual pattern would be to call it in a
241[`process.on('exit')`][] handler.
242
243```mjs
244import assert from 'node:assert';
245import process from 'node:process';
246
247const tracker = new assert.CallTracker();
248
249function func() {}
250
251// callsfunc() must be called exactly 1 time before tracker.verify().
252const callsfunc = tracker.calls(func, 1);
253
254callsfunc();
255
256// Calls tracker.verify() and verifies if all tracker.calls() functions have
257// been called exact times.
258process.on('exit', () => {
259  tracker.verify();
260});
261```
262
263```cjs
264const assert = require('node:assert');
265
266const tracker = new assert.CallTracker();
267
268function func() {}
269
270// callsfunc() must be called exactly 1 time before tracker.verify().
271const callsfunc = tracker.calls(func, 1);
272
273callsfunc();
274
275// Calls tracker.verify() and verifies if all tracker.calls() functions have
276// been called exact times.
277process.on('exit', () => {
278  tracker.verify();
279});
280```
281
282### `tracker.calls([fn][, exact])`
283
284<!-- YAML
285added:
286  - v14.2.0
287  - v12.19.0
288-->
289
290* `fn` {Function} **Default:** A no-op function.
291* `exact` {number} **Default:** `1`.
292* Returns: {Function} that wraps `fn`.
293
294The wrapper function is expected to be called exactly `exact` times. If the
295function has not been called exactly `exact` times when
296[`tracker.verify()`][] is called, then [`tracker.verify()`][] will throw an
297error.
298
299```mjs
300import assert from 'node:assert';
301
302// Creates call tracker.
303const tracker = new assert.CallTracker();
304
305function func() {}
306
307// Returns a function that wraps func() that must be called exact times
308// before tracker.verify().
309const callsfunc = tracker.calls(func);
310```
311
312```cjs
313const assert = require('node:assert');
314
315// Creates call tracker.
316const tracker = new assert.CallTracker();
317
318function func() {}
319
320// Returns a function that wraps func() that must be called exact times
321// before tracker.verify().
322const callsfunc = tracker.calls(func);
323```
324
325### `tracker.getCalls(fn)`
326
327<!-- YAML
328added: v18.8.0
329-->
330
331* `fn` {Function}.
332
333* Returns: {Array} with all the calls to a tracked function.
334
335* Object {Object}
336  * `thisArg` {Object}
337  * `arguments` {Array} the arguments passed to the tracked function
338
339```mjs
340import assert from 'node:assert';
341
342const tracker = new assert.CallTracker();
343
344function func() {}
345const callsfunc = tracker.calls(func);
346callsfunc(1, 2, 3);
347
348assert.deepStrictEqual(tracker.getCalls(callsfunc),
349                       [{ thisArg: undefined, arguments: [1, 2, 3] }]);
350```
351
352```cjs
353const assert = require('node:assert');
354
355// Creates call tracker.
356const tracker = new assert.CallTracker();
357
358function func() {}
359const callsfunc = tracker.calls(func);
360callsfunc(1, 2, 3);
361
362assert.deepStrictEqual(tracker.getCalls(callsfunc),
363                       [{ thisArg: undefined, arguments: [1, 2, 3] }]);
364```
365
366### `tracker.report()`
367
368<!-- YAML
369added:
370  - v14.2.0
371  - v12.19.0
372-->
373
374* Returns: {Array} of objects containing information about the wrapper functions
375  returned by [`tracker.calls()`][].
376* Object {Object}
377  * `message` {string}
378  * `actual` {number} The actual number of times the function was called.
379  * `expected` {number} The number of times the function was expected to be
380    called.
381  * `operator` {string} The name of the function that is wrapped.
382  * `stack` {Object} A stack trace of the function.
383
384The arrays contains information about the expected and actual number of calls of
385the functions that have not been called the expected number of times.
386
387```mjs
388import assert from 'node:assert';
389
390// Creates call tracker.
391const tracker = new assert.CallTracker();
392
393function func() {}
394
395// Returns a function that wraps func() that must be called exact times
396// before tracker.verify().
397const callsfunc = tracker.calls(func, 2);
398
399// Returns an array containing information on callsfunc()
400console.log(tracker.report());
401// [
402//  {
403//    message: 'Expected the func function to be executed 2 time(s) but was
404//    executed 0 time(s).',
405//    actual: 0,
406//    expected: 2,
407//    operator: 'func',
408//    stack: stack trace
409//  }
410// ]
411```
412
413```cjs
414const assert = require('node:assert');
415
416// Creates call tracker.
417const tracker = new assert.CallTracker();
418
419function func() {}
420
421// Returns a function that wraps func() that must be called exact times
422// before tracker.verify().
423const callsfunc = tracker.calls(func, 2);
424
425// Returns an array containing information on callsfunc()
426console.log(tracker.report());
427// [
428//  {
429//    message: 'Expected the func function to be executed 2 time(s) but was
430//    executed 0 time(s).',
431//    actual: 0,
432//    expected: 2,
433//    operator: 'func',
434//    stack: stack trace
435//  }
436// ]
437```
438
439### `tracker.reset([fn])`
440
441<!-- YAML
442added: v18.8.0
443-->
444
445* `fn` {Function} a tracked function to reset.
446
447Reset calls of the call tracker.
448If a tracked function is passed as an argument, the calls will be reset for it.
449If no arguments are passed, all tracked functions will be reset
450
451```mjs
452import assert from 'node:assert';
453
454const tracker = new assert.CallTracker();
455
456function func() {}
457const callsfunc = tracker.calls(func);
458
459callsfunc();
460// Tracker was called once
461assert.strictEqual(tracker.getCalls(callsfunc).length, 1);
462
463tracker.reset(callsfunc);
464assert.strictEqual(tracker.getCalls(callsfunc).length, 0);
465```
466
467```cjs
468const assert = require('node:assert');
469
470const tracker = new assert.CallTracker();
471
472function func() {}
473const callsfunc = tracker.calls(func);
474
475callsfunc();
476// Tracker was called once
477assert.strictEqual(tracker.getCalls(callsfunc).length, 1);
478
479tracker.reset(callsfunc);
480assert.strictEqual(tracker.getCalls(callsfunc).length, 0);
481```
482
483### `tracker.verify()`
484
485<!-- YAML
486added:
487  - v14.2.0
488  - v12.19.0
489-->
490
491Iterates through the list of functions passed to
492[`tracker.calls()`][] and will throw an error for functions that
493have not been called the expected number of times.
494
495```mjs
496import assert from 'node:assert';
497
498// Creates call tracker.
499const tracker = new assert.CallTracker();
500
501function func() {}
502
503// Returns a function that wraps func() that must be called exact times
504// before tracker.verify().
505const callsfunc = tracker.calls(func, 2);
506
507callsfunc();
508
509// Will throw an error since callsfunc() was only called once.
510tracker.verify();
511```
512
513```cjs
514const assert = require('node:assert');
515
516// Creates call tracker.
517const tracker = new assert.CallTracker();
518
519function func() {}
520
521// Returns a function that wraps func() that must be called exact times
522// before tracker.verify().
523const callsfunc = tracker.calls(func, 2);
524
525callsfunc();
526
527// Will throw an error since callsfunc() was only called once.
528tracker.verify();
529```
530
531## `assert(value[, message])`
532
533<!-- YAML
534added: v0.5.9
535-->
536
537* `value` {any} The input that is checked for being truthy.
538* `message` {string|Error}
539
540An alias of [`assert.ok()`][].
541
542## `assert.deepEqual(actual, expected[, message])`
543
544<!-- YAML
545added: v0.1.21
546changes:
547  - version: v18.0.0
548    pr-url: https://github.com/nodejs/node/pull/41020
549    description: Regular expressions lastIndex property is now compared as well.
550  - version:
551      - v16.0.0
552      - v14.18.0
553    pr-url: https://github.com/nodejs/node/pull/38113
554    description: In Legacy assertion mode, changed status from Deprecated to
555                 Legacy.
556  - version: v14.0.0
557    pr-url: https://github.com/nodejs/node/pull/30766
558    description: NaN is now treated as being identical if both sides are
559                 NaN.
560  - version: v12.0.0
561    pr-url: https://github.com/nodejs/node/pull/25008
562    description: The type tags are now properly compared and there are a couple
563                 minor comparison adjustments to make the check less surprising.
564  - version: v9.0.0
565    pr-url: https://github.com/nodejs/node/pull/15001
566    description: The `Error` names and messages are now properly compared.
567  - version: v8.0.0
568    pr-url: https://github.com/nodejs/node/pull/12142
569    description: The `Set` and `Map` content is also compared.
570  - version:
571      - v6.4.0
572      - v4.7.1
573    pr-url: https://github.com/nodejs/node/pull/8002
574    description: Typed array slices are handled correctly now.
575  - version:
576      - v6.1.0
577      - v4.5.0
578    pr-url: https://github.com/nodejs/node/pull/6432
579    description: Objects with circular references can be used as inputs now.
580  - version:
581      - v5.10.1
582      - v4.4.3
583    pr-url: https://github.com/nodejs/node/pull/5910
584    description: Handle non-`Uint8Array` typed arrays correctly.
585-->
586
587* `actual` {any}
588* `expected` {any}
589* `message` {string|Error}
590
591**Strict assertion mode**
592
593An alias of [`assert.deepStrictEqual()`][].
594
595**Legacy assertion mode**
596
597> Stability: 3 - Legacy: Use [`assert.deepStrictEqual()`][] instead.
598
599Tests for deep equality between the `actual` and `expected` parameters. Consider
600using [`assert.deepStrictEqual()`][] instead. [`assert.deepEqual()`][] can have
601surprising results.
602
603_Deep equality_ means that the enumerable "own" properties of child objects
604are also recursively evaluated by the following rules.
605
606### Comparison details
607
608* Primitive values are compared with the [`==` operator][],
609  with the exception of `NaN`. It is treated as being identical in case
610  both sides are `NaN`.
611* [Type tags][Object.prototype.toString()] of objects should be the same.
612* Only [enumerable "own" properties][] are considered.
613* [`Error`][] names and messages are always compared, even if these are not
614  enumerable properties.
615* [Object wrappers][] are compared both as objects and unwrapped values.
616* `Object` properties are compared unordered.
617* [`Map`][] keys and [`Set`][] items are compared unordered.
618* Recursion stops when both sides differ or both sides encounter a circular
619  reference.
620* Implementation does not test the [`[[Prototype]]`][prototype-spec] of
621  objects.
622* [`Symbol`][] properties are not compared.
623* [`WeakMap`][] and [`WeakSet`][] comparison does not rely on their values.
624* [`RegExp`][] lastIndex, flags, and source are always compared, even if these
625  are not enumerable properties.
626
627The following example does not throw an [`AssertionError`][] because the
628primitives are compared using the [`==` operator][].
629
630```mjs
631import assert from 'node:assert';
632// WARNING: This does not throw an AssertionError!
633
634assert.deepEqual('+00000000', false);
635```
636
637```cjs
638const assert = require('node:assert');
639// WARNING: This does not throw an AssertionError!
640
641assert.deepEqual('+00000000', false);
642```
643
644"Deep" equality means that the enumerable "own" properties of child objects
645are evaluated also:
646
647```mjs
648import assert from 'node:assert';
649
650const obj1 = {
651  a: {
652    b: 1,
653  },
654};
655const obj2 = {
656  a: {
657    b: 2,
658  },
659};
660const obj3 = {
661  a: {
662    b: 1,
663  },
664};
665const obj4 = Object.create(obj1);
666
667assert.deepEqual(obj1, obj1);
668// OK
669
670// Values of b are different:
671assert.deepEqual(obj1, obj2);
672// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
673
674assert.deepEqual(obj1, obj3);
675// OK
676
677// Prototypes are ignored:
678assert.deepEqual(obj1, obj4);
679// AssertionError: { a: { b: 1 } } deepEqual {}
680```
681
682```cjs
683const assert = require('node:assert');
684
685const obj1 = {
686  a: {
687    b: 1,
688  },
689};
690const obj2 = {
691  a: {
692    b: 2,
693  },
694};
695const obj3 = {
696  a: {
697    b: 1,
698  },
699};
700const obj4 = Object.create(obj1);
701
702assert.deepEqual(obj1, obj1);
703// OK
704
705// Values of b are different:
706assert.deepEqual(obj1, obj2);
707// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
708
709assert.deepEqual(obj1, obj3);
710// OK
711
712// Prototypes are ignored:
713assert.deepEqual(obj1, obj4);
714// AssertionError: { a: { b: 1 } } deepEqual {}
715```
716
717If the values are not equal, an [`AssertionError`][] is thrown with a `message`
718property set equal to the value of the `message` parameter. If the `message`
719parameter is undefined, a default error message is assigned. If the `message`
720parameter is an instance of an [`Error`][] then it will be thrown instead of the
721[`AssertionError`][].
722
723## `assert.deepStrictEqual(actual, expected[, message])`
724
725<!-- YAML
726added: v1.2.0
727changes:
728  - version: v18.0.0
729    pr-url: https://github.com/nodejs/node/pull/41020
730    description: Regular expressions lastIndex property is now compared as well.
731  - version: v9.0.0
732    pr-url: https://github.com/nodejs/node/pull/15169
733    description: Enumerable symbol properties are now compared.
734  - version: v9.0.0
735    pr-url: https://github.com/nodejs/node/pull/15036
736    description: The `NaN` is now compared using the
737              [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero)
738              comparison.
739  - version: v8.5.0
740    pr-url: https://github.com/nodejs/node/pull/15001
741    description: The `Error` names and messages are now properly compared.
742  - version: v8.0.0
743    pr-url: https://github.com/nodejs/node/pull/12142
744    description: The `Set` and `Map` content is also compared.
745  - version:
746    - v6.4.0
747    - v4.7.1
748    pr-url: https://github.com/nodejs/node/pull/8002
749    description: Typed array slices are handled correctly now.
750  - version: v6.1.0
751    pr-url: https://github.com/nodejs/node/pull/6432
752    description: Objects with circular references can be used as inputs now.
753  - version:
754    - v5.10.1
755    - v4.4.3
756    pr-url: https://github.com/nodejs/node/pull/5910
757    description: Handle non-`Uint8Array` typed arrays correctly.
758-->
759
760* `actual` {any}
761* `expected` {any}
762* `message` {string|Error}
763
764Tests for deep equality between the `actual` and `expected` parameters.
765"Deep" equality means that the enumerable "own" properties of child objects
766are recursively evaluated also by the following rules.
767
768### Comparison details
769
770* Primitive values are compared using [`Object.is()`][].
771* [Type tags][Object.prototype.toString()] of objects should be the same.
772* [`[[Prototype]]`][prototype-spec] of objects are compared using
773  the [`===` operator][].
774* Only [enumerable "own" properties][] are considered.
775* [`Error`][] names and messages are always compared, even if these are not
776  enumerable properties.
777* Enumerable own [`Symbol`][] properties are compared as well.
778* [Object wrappers][] are compared both as objects and unwrapped values.
779* `Object` properties are compared unordered.
780* [`Map`][] keys and [`Set`][] items are compared unordered.
781* Recursion stops when both sides differ or both sides encounter a circular
782  reference.
783* [`WeakMap`][] and [`WeakSet`][] comparison does not rely on their values. See
784  below for further details.
785* [`RegExp`][] lastIndex, flags, and source are always compared, even if these
786  are not enumerable properties.
787
788```mjs
789import assert from 'node:assert/strict';
790
791// This fails because 1 !== '1'.
792assert.deepStrictEqual({ a: 1 }, { a: '1' });
793// AssertionError: Expected inputs to be strictly deep-equal:
794// + actual - expected
795//
796//   {
797// +   a: 1
798// -   a: '1'
799//   }
800
801// The following objects don't have own properties
802const date = new Date();
803const object = {};
804const fakeDate = {};
805Object.setPrototypeOf(fakeDate, Date.prototype);
806
807// Different [[Prototype]]:
808assert.deepStrictEqual(object, fakeDate);
809// AssertionError: Expected inputs to be strictly deep-equal:
810// + actual - expected
811//
812// + {}
813// - Date {}
814
815// Different type tags:
816assert.deepStrictEqual(date, fakeDate);
817// AssertionError: Expected inputs to be strictly deep-equal:
818// + actual - expected
819//
820// + 2018-04-26T00:49:08.604Z
821// - Date {}
822
823assert.deepStrictEqual(NaN, NaN);
824// OK because Object.is(NaN, NaN) is true.
825
826// Different unwrapped numbers:
827assert.deepStrictEqual(new Number(1), new Number(2));
828// AssertionError: Expected inputs to be strictly deep-equal:
829// + actual - expected
830//
831// + [Number: 1]
832// - [Number: 2]
833
834assert.deepStrictEqual(new String('foo'), Object('foo'));
835// OK because the object and the string are identical when unwrapped.
836
837assert.deepStrictEqual(-0, -0);
838// OK
839
840// Different zeros:
841assert.deepStrictEqual(0, -0);
842// AssertionError: Expected inputs to be strictly deep-equal:
843// + actual - expected
844//
845// + 0
846// - -0
847
848const symbol1 = Symbol();
849const symbol2 = Symbol();
850assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
851// OK, because it is the same symbol on both objects.
852
853assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
854// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:
855//
856// {
857//   [Symbol()]: 1
858// }
859
860const weakMap1 = new WeakMap();
861const weakMap2 = new WeakMap([[{}, {}]]);
862const weakMap3 = new WeakMap();
863weakMap3.unequal = true;
864
865assert.deepStrictEqual(weakMap1, weakMap2);
866// OK, because it is impossible to compare the entries
867
868// Fails because weakMap3 has a property that weakMap1 does not contain:
869assert.deepStrictEqual(weakMap1, weakMap3);
870// AssertionError: Expected inputs to be strictly deep-equal:
871// + actual - expected
872//
873//   WeakMap {
874// +   [items unknown]
875// -   [items unknown],
876// -   unequal: true
877//   }
878```
879
880```cjs
881const assert = require('node:assert/strict');
882
883// This fails because 1 !== '1'.
884assert.deepStrictEqual({ a: 1 }, { a: '1' });
885// AssertionError: Expected inputs to be strictly deep-equal:
886// + actual - expected
887//
888//   {
889// +   a: 1
890// -   a: '1'
891//   }
892
893// The following objects don't have own properties
894const date = new Date();
895const object = {};
896const fakeDate = {};
897Object.setPrototypeOf(fakeDate, Date.prototype);
898
899// Different [[Prototype]]:
900assert.deepStrictEqual(object, fakeDate);
901// AssertionError: Expected inputs to be strictly deep-equal:
902// + actual - expected
903//
904// + {}
905// - Date {}
906
907// Different type tags:
908assert.deepStrictEqual(date, fakeDate);
909// AssertionError: Expected inputs to be strictly deep-equal:
910// + actual - expected
911//
912// + 2018-04-26T00:49:08.604Z
913// - Date {}
914
915assert.deepStrictEqual(NaN, NaN);
916// OK because Object.is(NaN, NaN) is true.
917
918// Different unwrapped numbers:
919assert.deepStrictEqual(new Number(1), new Number(2));
920// AssertionError: Expected inputs to be strictly deep-equal:
921// + actual - expected
922//
923// + [Number: 1]
924// - [Number: 2]
925
926assert.deepStrictEqual(new String('foo'), Object('foo'));
927// OK because the object and the string are identical when unwrapped.
928
929assert.deepStrictEqual(-0, -0);
930// OK
931
932// Different zeros:
933assert.deepStrictEqual(0, -0);
934// AssertionError: Expected inputs to be strictly deep-equal:
935// + actual - expected
936//
937// + 0
938// - -0
939
940const symbol1 = Symbol();
941const symbol2 = Symbol();
942assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
943// OK, because it is the same symbol on both objects.
944
945assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
946// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:
947//
948// {
949//   [Symbol()]: 1
950// }
951
952const weakMap1 = new WeakMap();
953const weakMap2 = new WeakMap([[{}, {}]]);
954const weakMap3 = new WeakMap();
955weakMap3.unequal = true;
956
957assert.deepStrictEqual(weakMap1, weakMap2);
958// OK, because it is impossible to compare the entries
959
960// Fails because weakMap3 has a property that weakMap1 does not contain:
961assert.deepStrictEqual(weakMap1, weakMap3);
962// AssertionError: Expected inputs to be strictly deep-equal:
963// + actual - expected
964//
965//   WeakMap {
966// +   [items unknown]
967// -   [items unknown],
968// -   unequal: true
969//   }
970```
971
972If the values are not equal, an [`AssertionError`][] is thrown with a `message`
973property set equal to the value of the `message` parameter. If the `message`
974parameter is undefined, a default error message is assigned. If the `message`
975parameter is an instance of an [`Error`][] then it will be thrown instead of the
976`AssertionError`.
977
978## `assert.doesNotMatch(string, regexp[, message])`
979
980<!-- YAML
981added:
982  - v13.6.0
983  - v12.16.0
984changes:
985  - version: v16.0.0
986    pr-url: https://github.com/nodejs/node/pull/38111
987    description: This API is no longer experimental.
988-->
989
990* `string` {string}
991* `regexp` {RegExp}
992* `message` {string|Error}
993
994Expects the `string` input not to match the regular expression.
995
996```mjs
997import assert from 'node:assert/strict';
998
999assert.doesNotMatch('I will fail', /fail/);
1000// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
1001
1002assert.doesNotMatch(123, /pass/);
1003// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
1004
1005assert.doesNotMatch('I will pass', /different/);
1006// OK
1007```
1008
1009```cjs
1010const assert = require('node:assert/strict');
1011
1012assert.doesNotMatch('I will fail', /fail/);
1013// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
1014
1015assert.doesNotMatch(123, /pass/);
1016// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
1017
1018assert.doesNotMatch('I will pass', /different/);
1019// OK
1020```
1021
1022If the values do match, or if the `string` argument is of another type than
1023`string`, an [`AssertionError`][] is thrown with a `message` property set equal
1024to the value of the `message` parameter. If the `message` parameter is
1025undefined, a default error message is assigned. If the `message` parameter is an
1026instance of an [`Error`][] then it will be thrown instead of the
1027[`AssertionError`][].
1028
1029## `assert.doesNotReject(asyncFn[, error][, message])`
1030
1031<!-- YAML
1032added: v10.0.0
1033-->
1034
1035* `asyncFn` {Function|Promise}
1036* `error` {RegExp|Function}
1037* `message` {string}
1038
1039Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
1040calls the function and awaits the returned promise to complete. It will then
1041check that the promise is not rejected.
1042
1043If `asyncFn` is a function and it throws an error synchronously,
1044`assert.doesNotReject()` will return a rejected `Promise` with that error. If
1045the function does not return a promise, `assert.doesNotReject()` will return a
1046rejected `Promise` with an [`ERR_INVALID_RETURN_VALUE`][] error. In both cases
1047the error handler is skipped.
1048
1049Using `assert.doesNotReject()` is actually not useful because there is little
1050benefit in catching a rejection and then rejecting it again. Instead, consider
1051adding a comment next to the specific code path that should not reject and keep
1052error messages as expressive as possible.
1053
1054If specified, `error` can be a [`Class`][], [`RegExp`][], or a validation
1055function. See [`assert.throws()`][] for more details.
1056
1057Besides the async nature to await the completion behaves identically to
1058[`assert.doesNotThrow()`][].
1059
1060```mjs
1061import assert from 'node:assert/strict';
1062
1063await assert.doesNotReject(
1064  async () => {
1065    throw new TypeError('Wrong value');
1066  },
1067  SyntaxError,
1068);
1069```
1070
1071```cjs
1072const assert = require('node:assert/strict');
1073
1074(async () => {
1075  await assert.doesNotReject(
1076    async () => {
1077      throw new TypeError('Wrong value');
1078    },
1079    SyntaxError,
1080  );
1081})();
1082```
1083
1084```mjs
1085import assert from 'node:assert/strict';
1086
1087assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
1088  .then(() => {
1089    // ...
1090  });
1091```
1092
1093```cjs
1094const assert = require('node:assert/strict');
1095
1096assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
1097  .then(() => {
1098    // ...
1099  });
1100```
1101
1102## `assert.doesNotThrow(fn[, error][, message])`
1103
1104<!-- YAML
1105added: v0.1.21
1106changes:
1107  - version:
1108    - v5.11.0
1109    - v4.4.5
1110    pr-url: https://github.com/nodejs/node/pull/2407
1111    description: The `message` parameter is respected now.
1112  - version: v4.2.0
1113    pr-url: https://github.com/nodejs/node/pull/3276
1114    description: The `error` parameter can now be an arrow function.
1115-->
1116
1117* `fn` {Function}
1118* `error` {RegExp|Function}
1119* `message` {string}
1120
1121Asserts that the function `fn` does not throw an error.
1122
1123Using `assert.doesNotThrow()` is actually not useful because there
1124is no benefit in catching an error and then rethrowing it. Instead, consider
1125adding a comment next to the specific code path that should not throw and keep
1126error messages as expressive as possible.
1127
1128When `assert.doesNotThrow()` is called, it will immediately call the `fn`
1129function.
1130
1131If an error is thrown and it is the same type as that specified by the `error`
1132parameter, then an [`AssertionError`][] is thrown. If the error is of a
1133different type, or if the `error` parameter is undefined, the error is
1134propagated back to the caller.
1135
1136If specified, `error` can be a [`Class`][], [`RegExp`][], or a validation
1137function. See [`assert.throws()`][] for more details.
1138
1139The following, for instance, will throw the [`TypeError`][] because there is no
1140matching error type in the assertion:
1141
1142```mjs
1143import assert from 'node:assert/strict';
1144
1145assert.doesNotThrow(
1146  () => {
1147    throw new TypeError('Wrong value');
1148  },
1149  SyntaxError,
1150);
1151```
1152
1153```cjs
1154const assert = require('node:assert/strict');
1155
1156assert.doesNotThrow(
1157  () => {
1158    throw new TypeError('Wrong value');
1159  },
1160  SyntaxError,
1161);
1162```
1163
1164However, the following will result in an [`AssertionError`][] with the message
1165'Got unwanted exception...':
1166
1167```mjs
1168import assert from 'node:assert/strict';
1169
1170assert.doesNotThrow(
1171  () => {
1172    throw new TypeError('Wrong value');
1173  },
1174  TypeError,
1175);
1176```
1177
1178```cjs
1179const assert = require('node:assert/strict');
1180
1181assert.doesNotThrow(
1182  () => {
1183    throw new TypeError('Wrong value');
1184  },
1185  TypeError,
1186);
1187```
1188
1189If an [`AssertionError`][] is thrown and a value is provided for the `message`
1190parameter, the value of `message` will be appended to the [`AssertionError`][]
1191message:
1192
1193```mjs
1194import assert from 'node:assert/strict';
1195
1196assert.doesNotThrow(
1197  () => {
1198    throw new TypeError('Wrong value');
1199  },
1200  /Wrong value/,
1201  'Whoops',
1202);
1203// Throws: AssertionError: Got unwanted exception: Whoops
1204```
1205
1206```cjs
1207const assert = require('node:assert/strict');
1208
1209assert.doesNotThrow(
1210  () => {
1211    throw new TypeError('Wrong value');
1212  },
1213  /Wrong value/,
1214  'Whoops',
1215);
1216// Throws: AssertionError: Got unwanted exception: Whoops
1217```
1218
1219## `assert.equal(actual, expected[, message])`
1220
1221<!-- YAML
1222added: v0.1.21
1223changes:
1224  - version:
1225      - v16.0.0
1226      - v14.18.0
1227    pr-url: https://github.com/nodejs/node/pull/38113
1228    description: In Legacy assertion mode, changed status from Deprecated to
1229                 Legacy.
1230  - version: v14.0.0
1231    pr-url: https://github.com/nodejs/node/pull/30766
1232    description: NaN is now treated as being identical if both sides are
1233                 NaN.
1234-->
1235
1236* `actual` {any}
1237* `expected` {any}
1238* `message` {string|Error}
1239
1240**Strict assertion mode**
1241
1242An alias of [`assert.strictEqual()`][].
1243
1244**Legacy assertion mode**
1245
1246> Stability: 3 - Legacy: Use [`assert.strictEqual()`][] instead.
1247
1248Tests shallow, coercive equality between the `actual` and `expected` parameters
1249using the [`==` operator][]. `NaN` is specially handled
1250and treated as being identical if both sides are `NaN`.
1251
1252```mjs
1253import assert from 'node:assert';
1254
1255assert.equal(1, 1);
1256// OK, 1 == 1
1257assert.equal(1, '1');
1258// OK, 1 == '1'
1259assert.equal(NaN, NaN);
1260// OK
1261
1262assert.equal(1, 2);
1263// AssertionError: 1 == 2
1264assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
1265// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
1266```
1267
1268```cjs
1269const assert = require('node:assert');
1270
1271assert.equal(1, 1);
1272// OK, 1 == 1
1273assert.equal(1, '1');
1274// OK, 1 == '1'
1275assert.equal(NaN, NaN);
1276// OK
1277
1278assert.equal(1, 2);
1279// AssertionError: 1 == 2
1280assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
1281// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
1282```
1283
1284If the values are not equal, an [`AssertionError`][] is thrown with a `message`
1285property set equal to the value of the `message` parameter. If the `message`
1286parameter is undefined, a default error message is assigned. If the `message`
1287parameter is an instance of an [`Error`][] then it will be thrown instead of the
1288`AssertionError`.
1289
1290## `assert.fail([message])`
1291
1292<!-- YAML
1293added: v0.1.21
1294-->
1295
1296* `message` {string|Error} **Default:** `'Failed'`
1297
1298Throws an [`AssertionError`][] with the provided error message or a default
1299error message. If the `message` parameter is an instance of an [`Error`][] then
1300it will be thrown instead of the [`AssertionError`][].
1301
1302```mjs
1303import assert from 'node:assert/strict';
1304
1305assert.fail();
1306// AssertionError [ERR_ASSERTION]: Failed
1307
1308assert.fail('boom');
1309// AssertionError [ERR_ASSERTION]: boom
1310
1311assert.fail(new TypeError('need array'));
1312// TypeError: need array
1313```
1314
1315```cjs
1316const assert = require('node:assert/strict');
1317
1318assert.fail();
1319// AssertionError [ERR_ASSERTION]: Failed
1320
1321assert.fail('boom');
1322// AssertionError [ERR_ASSERTION]: boom
1323
1324assert.fail(new TypeError('need array'));
1325// TypeError: need array
1326```
1327
1328Using `assert.fail()` with more than two arguments is possible but deprecated.
1329See below for further details.
1330
1331## `assert.fail(actual, expected[, message[, operator[, stackStartFn]]])`
1332
1333<!-- YAML
1334added: v0.1.21
1335changes:
1336  - version: v10.0.0
1337    pr-url: https://github.com/nodejs/node/pull/18418
1338    description: Calling `assert.fail()` with more than one argument is
1339                 deprecated and emits a warning.
1340-->
1341
1342> Stability: 0 - Deprecated: Use `assert.fail([message])` or other assert
1343> functions instead.
1344
1345* `actual` {any}
1346* `expected` {any}
1347* `message` {string|Error}
1348* `operator` {string} **Default:** `'!='`
1349* `stackStartFn` {Function} **Default:** `assert.fail`
1350
1351If `message` is falsy, the error message is set as the values of `actual` and
1352`expected` separated by the provided `operator`. If just the two `actual` and
1353`expected` arguments are provided, `operator` will default to `'!='`. If
1354`message` is provided as third argument it will be used as the error message and
1355the other arguments will be stored as properties on the thrown object. If
1356`stackStartFn` is provided, all stack frames above that function will be
1357removed from stacktrace (see [`Error.captureStackTrace`][]). If no arguments are
1358given, the default message `Failed` will be used.
1359
1360```mjs
1361import assert from 'node:assert/strict';
1362
1363assert.fail('a', 'b');
1364// AssertionError [ERR_ASSERTION]: 'a' != 'b'
1365
1366assert.fail(1, 2, undefined, '>');
1367// AssertionError [ERR_ASSERTION]: 1 > 2
1368
1369assert.fail(1, 2, 'fail');
1370// AssertionError [ERR_ASSERTION]: fail
1371
1372assert.fail(1, 2, 'whoops', '>');
1373// AssertionError [ERR_ASSERTION]: whoops
1374
1375assert.fail(1, 2, new TypeError('need array'));
1376// TypeError: need array
1377```
1378
1379```cjs
1380const assert = require('node:assert/strict');
1381
1382assert.fail('a', 'b');
1383// AssertionError [ERR_ASSERTION]: 'a' != 'b'
1384
1385assert.fail(1, 2, undefined, '>');
1386// AssertionError [ERR_ASSERTION]: 1 > 2
1387
1388assert.fail(1, 2, 'fail');
1389// AssertionError [ERR_ASSERTION]: fail
1390
1391assert.fail(1, 2, 'whoops', '>');
1392// AssertionError [ERR_ASSERTION]: whoops
1393
1394assert.fail(1, 2, new TypeError('need array'));
1395// TypeError: need array
1396```
1397
1398In the last three cases `actual`, `expected`, and `operator` have no
1399influence on the error message.
1400
1401Example use of `stackStartFn` for truncating the exception's stacktrace:
1402
1403```mjs
1404import assert from 'node:assert/strict';
1405
1406function suppressFrame() {
1407  assert.fail('a', 'b', undefined, '!==', suppressFrame);
1408}
1409suppressFrame();
1410// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
1411//     at repl:1:1
1412//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)
1413//     ...
1414```
1415
1416```cjs
1417const assert = require('node:assert/strict');
1418
1419function suppressFrame() {
1420  assert.fail('a', 'b', undefined, '!==', suppressFrame);
1421}
1422suppressFrame();
1423// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
1424//     at repl:1:1
1425//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)
1426//     ...
1427```
1428
1429## `assert.ifError(value)`
1430
1431<!-- YAML
1432added: v0.1.97
1433changes:
1434  - version: v10.0.0
1435    pr-url: https://github.com/nodejs/node/pull/18247
1436    description: Instead of throwing the original error it is now wrapped into
1437                 an [`AssertionError`][] that contains the full stack trace.
1438  - version: v10.0.0
1439    pr-url: https://github.com/nodejs/node/pull/18247
1440    description: Value may now only be `undefined` or `null`. Before all falsy
1441                 values were handled the same as `null` and did not throw.
1442-->
1443
1444* `value` {any}
1445
1446Throws `value` if `value` is not `undefined` or `null`. This is useful when
1447testing the `error` argument in callbacks. The stack trace contains all frames
1448from the error passed to `ifError()` including the potential new frames for
1449`ifError()` itself.
1450
1451```mjs
1452import assert from 'node:assert/strict';
1453
1454assert.ifError(null);
1455// OK
1456assert.ifError(0);
1457// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
1458assert.ifError('error');
1459// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
1460assert.ifError(new Error());
1461// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error
1462
1463// Create some random error frames.
1464let err;
1465(function errorFrame() {
1466  err = new Error('test error');
1467})();
1468
1469(function ifErrorFrame() {
1470  assert.ifError(err);
1471})();
1472// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
1473//     at ifErrorFrame
1474//     at errorFrame
1475```
1476
1477```cjs
1478const assert = require('node:assert/strict');
1479
1480assert.ifError(null);
1481// OK
1482assert.ifError(0);
1483// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
1484assert.ifError('error');
1485// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
1486assert.ifError(new Error());
1487// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error
1488
1489// Create some random error frames.
1490let err;
1491(function errorFrame() {
1492  err = new Error('test error');
1493})();
1494
1495(function ifErrorFrame() {
1496  assert.ifError(err);
1497})();
1498// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
1499//     at ifErrorFrame
1500//     at errorFrame
1501```
1502
1503## `assert.match(string, regexp[, message])`
1504
1505<!-- YAML
1506added:
1507  - v13.6.0
1508  - v12.16.0
1509changes:
1510  - version: v16.0.0
1511    pr-url: https://github.com/nodejs/node/pull/38111
1512    description: This API is no longer experimental.
1513-->
1514
1515* `string` {string}
1516* `regexp` {RegExp}
1517* `message` {string|Error}
1518
1519Expects the `string` input to match the regular expression.
1520
1521```mjs
1522import assert from 'node:assert/strict';
1523
1524assert.match('I will fail', /pass/);
1525// AssertionError [ERR_ASSERTION]: The input did not match the regular ...
1526
1527assert.match(123, /pass/);
1528// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
1529
1530assert.match('I will pass', /pass/);
1531// OK
1532```
1533
1534```cjs
1535const assert = require('node:assert/strict');
1536
1537assert.match('I will fail', /pass/);
1538// AssertionError [ERR_ASSERTION]: The input did not match the regular ...
1539
1540assert.match(123, /pass/);
1541// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
1542
1543assert.match('I will pass', /pass/);
1544// OK
1545```
1546
1547If the values do not match, or if the `string` argument is of another type than
1548`string`, an [`AssertionError`][] is thrown with a `message` property set equal
1549to the value of the `message` parameter. If the `message` parameter is
1550undefined, a default error message is assigned. If the `message` parameter is an
1551instance of an [`Error`][] then it will be thrown instead of the
1552[`AssertionError`][].
1553
1554## `assert.notDeepEqual(actual, expected[, message])`
1555
1556<!-- YAML
1557added: v0.1.21
1558changes:
1559  - version:
1560      - v16.0.0
1561      - v14.18.0
1562    pr-url: https://github.com/nodejs/node/pull/38113
1563    description: In Legacy assertion mode, changed status from Deprecated to
1564                 Legacy.
1565  - version: v14.0.0
1566    pr-url: https://github.com/nodejs/node/pull/30766
1567    description: NaN is now treated as being identical if both sides are
1568                 NaN.
1569  - version: v9.0.0
1570    pr-url: https://github.com/nodejs/node/pull/15001
1571    description: The `Error` names and messages are now properly compared.
1572  - version: v8.0.0
1573    pr-url: https://github.com/nodejs/node/pull/12142
1574    description: The `Set` and `Map` content is also compared.
1575  - version:
1576      - v6.4.0
1577      - v4.7.1
1578    pr-url: https://github.com/nodejs/node/pull/8002
1579    description: Typed array slices are handled correctly now.
1580  - version:
1581      - v6.1.0
1582      - v4.5.0
1583    pr-url: https://github.com/nodejs/node/pull/6432
1584    description: Objects with circular references can be used as inputs now.
1585  - version:
1586      - v5.10.1
1587      - v4.4.3
1588    pr-url: https://github.com/nodejs/node/pull/5910
1589    description: Handle non-`Uint8Array` typed arrays correctly.
1590-->
1591
1592* `actual` {any}
1593* `expected` {any}
1594* `message` {string|Error}
1595
1596**Strict assertion mode**
1597
1598An alias of [`assert.notDeepStrictEqual()`][].
1599
1600**Legacy assertion mode**
1601
1602> Stability: 3 - Legacy: Use [`assert.notDeepStrictEqual()`][] instead.
1603
1604Tests for any deep inequality. Opposite of [`assert.deepEqual()`][].
1605
1606```mjs
1607import assert from 'node:assert';
1608
1609const obj1 = {
1610  a: {
1611    b: 1,
1612  },
1613};
1614const obj2 = {
1615  a: {
1616    b: 2,
1617  },
1618};
1619const obj3 = {
1620  a: {
1621    b: 1,
1622  },
1623};
1624const obj4 = Object.create(obj1);
1625
1626assert.notDeepEqual(obj1, obj1);
1627// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
1628
1629assert.notDeepEqual(obj1, obj2);
1630// OK
1631
1632assert.notDeepEqual(obj1, obj3);
1633// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
1634
1635assert.notDeepEqual(obj1, obj4);
1636// OK
1637```
1638
1639```cjs
1640const assert = require('node:assert');
1641
1642const obj1 = {
1643  a: {
1644    b: 1,
1645  },
1646};
1647const obj2 = {
1648  a: {
1649    b: 2,
1650  },
1651};
1652const obj3 = {
1653  a: {
1654    b: 1,
1655  },
1656};
1657const obj4 = Object.create(obj1);
1658
1659assert.notDeepEqual(obj1, obj1);
1660// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
1661
1662assert.notDeepEqual(obj1, obj2);
1663// OK
1664
1665assert.notDeepEqual(obj1, obj3);
1666// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
1667
1668assert.notDeepEqual(obj1, obj4);
1669// OK
1670```
1671
1672If the values are deeply equal, an [`AssertionError`][] is thrown with a
1673`message` property set equal to the value of the `message` parameter. If the
1674`message` parameter is undefined, a default error message is assigned. If the
1675`message` parameter is an instance of an [`Error`][] then it will be thrown
1676instead of the `AssertionError`.
1677
1678## `assert.notDeepStrictEqual(actual, expected[, message])`
1679
1680<!-- YAML
1681added: v1.2.0
1682changes:
1683  - version: v9.0.0
1684    pr-url: https://github.com/nodejs/node/pull/15398
1685    description: The `-0` and `+0` are not considered equal anymore.
1686  - version: v9.0.0
1687    pr-url: https://github.com/nodejs/node/pull/15036
1688    description: The `NaN` is now compared using the
1689              [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero)
1690              comparison.
1691  - version: v9.0.0
1692    pr-url: https://github.com/nodejs/node/pull/15001
1693    description: The `Error` names and messages are now properly compared.
1694  - version: v8.0.0
1695    pr-url: https://github.com/nodejs/node/pull/12142
1696    description: The `Set` and `Map` content is also compared.
1697  - version:
1698    - v6.4.0
1699    - v4.7.1
1700    pr-url: https://github.com/nodejs/node/pull/8002
1701    description: Typed array slices are handled correctly now.
1702  - version: v6.1.0
1703    pr-url: https://github.com/nodejs/node/pull/6432
1704    description: Objects with circular references can be used as inputs now.
1705  - version:
1706    - v5.10.1
1707    - v4.4.3
1708    pr-url: https://github.com/nodejs/node/pull/5910
1709    description: Handle non-`Uint8Array` typed arrays correctly.
1710-->
1711
1712* `actual` {any}
1713* `expected` {any}
1714* `message` {string|Error}
1715
1716Tests for deep strict inequality. Opposite of [`assert.deepStrictEqual()`][].
1717
1718```mjs
1719import assert from 'node:assert/strict';
1720
1721assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
1722// OK
1723```
1724
1725```cjs
1726const assert = require('node:assert/strict');
1727
1728assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
1729// OK
1730```
1731
1732If the values are deeply and strictly equal, an [`AssertionError`][] is thrown
1733with a `message` property set equal to the value of the `message` parameter. If
1734the `message` parameter is undefined, a default error message is assigned. If
1735the `message` parameter is an instance of an [`Error`][] then it will be thrown
1736instead of the [`AssertionError`][].
1737
1738## `assert.notEqual(actual, expected[, message])`
1739
1740<!-- YAML
1741added: v0.1.21
1742changes:
1743  - version:
1744      - v16.0.0
1745      - v14.18.0
1746    pr-url: https://github.com/nodejs/node/pull/38113
1747    description: In Legacy assertion mode, changed status from Deprecated to
1748                 Legacy.
1749  - version: v14.0.0
1750    pr-url: https://github.com/nodejs/node/pull/30766
1751    description: NaN is now treated as being identical if both sides are
1752                 NaN.
1753-->
1754
1755* `actual` {any}
1756* `expected` {any}
1757* `message` {string|Error}
1758
1759**Strict assertion mode**
1760
1761An alias of [`assert.notStrictEqual()`][].
1762
1763**Legacy assertion mode**
1764
1765> Stability: 3 - Legacy: Use [`assert.notStrictEqual()`][] instead.
1766
1767Tests shallow, coercive inequality with the [`!=` operator][]. `NaN` is
1768specially handled and treated as being identical if both sides are `NaN`.
1769
1770```mjs
1771import assert from 'node:assert';
1772
1773assert.notEqual(1, 2);
1774// OK
1775
1776assert.notEqual(1, 1);
1777// AssertionError: 1 != 1
1778
1779assert.notEqual(1, '1');
1780// AssertionError: 1 != '1'
1781```
1782
1783```cjs
1784const assert = require('node:assert');
1785
1786assert.notEqual(1, 2);
1787// OK
1788
1789assert.notEqual(1, 1);
1790// AssertionError: 1 != 1
1791
1792assert.notEqual(1, '1');
1793// AssertionError: 1 != '1'
1794```
1795
1796If the values are equal, an [`AssertionError`][] is thrown with a `message`
1797property set equal to the value of the `message` parameter. If the `message`
1798parameter is undefined, a default error message is assigned. If the `message`
1799parameter is an instance of an [`Error`][] then it will be thrown instead of the
1800`AssertionError`.
1801
1802## `assert.notStrictEqual(actual, expected[, message])`
1803
1804<!-- YAML
1805added: v0.1.21
1806changes:
1807  - version: v10.0.0
1808    pr-url: https://github.com/nodejs/node/pull/17003
1809    description: Used comparison changed from Strict Equality to `Object.is()`.
1810-->
1811
1812* `actual` {any}
1813* `expected` {any}
1814* `message` {string|Error}
1815
1816Tests strict inequality between the `actual` and `expected` parameters as
1817determined by [`Object.is()`][].
1818
1819```mjs
1820import assert from 'node:assert/strict';
1821
1822assert.notStrictEqual(1, 2);
1823// OK
1824
1825assert.notStrictEqual(1, 1);
1826// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
1827//
1828// 1
1829
1830assert.notStrictEqual(1, '1');
1831// OK
1832```
1833
1834```cjs
1835const assert = require('node:assert/strict');
1836
1837assert.notStrictEqual(1, 2);
1838// OK
1839
1840assert.notStrictEqual(1, 1);
1841// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
1842//
1843// 1
1844
1845assert.notStrictEqual(1, '1');
1846// OK
1847```
1848
1849If the values are strictly equal, an [`AssertionError`][] is thrown with a
1850`message` property set equal to the value of the `message` parameter. If the
1851`message` parameter is undefined, a default error message is assigned. If the
1852`message` parameter is an instance of an [`Error`][] then it will be thrown
1853instead of the `AssertionError`.
1854
1855## `assert.ok(value[, message])`
1856
1857<!-- YAML
1858added: v0.1.21
1859changes:
1860  - version: v10.0.0
1861    pr-url: https://github.com/nodejs/node/pull/18319
1862    description: The `assert.ok()` (no arguments) will now use a predefined
1863                 error message.
1864-->
1865
1866* `value` {any}
1867* `message` {string|Error}
1868
1869Tests if `value` is truthy. It is equivalent to
1870`assert.equal(!!value, true, message)`.
1871
1872If `value` is not truthy, an [`AssertionError`][] is thrown with a `message`
1873property set equal to the value of the `message` parameter. If the `message`
1874parameter is `undefined`, a default error message is assigned. If the `message`
1875parameter is an instance of an [`Error`][] then it will be thrown instead of the
1876`AssertionError`.
1877If no arguments are passed in at all `message` will be set to the string:
1878``'No value argument passed to `assert.ok()`'``.
1879
1880Be aware that in the `repl` the error message will be different to the one
1881thrown in a file! See below for further details.
1882
1883```mjs
1884import assert from 'node:assert/strict';
1885
1886assert.ok(true);
1887// OK
1888assert.ok(1);
1889// OK
1890
1891assert.ok();
1892// AssertionError: No value argument passed to `assert.ok()`
1893
1894assert.ok(false, 'it\'s false');
1895// AssertionError: it's false
1896
1897// In the repl:
1898assert.ok(typeof 123 === 'string');
1899// AssertionError: false == true
1900
1901// In a file (e.g. test.js):
1902assert.ok(typeof 123 === 'string');
1903// AssertionError: The expression evaluated to a falsy value:
1904//
1905//   assert.ok(typeof 123 === 'string')
1906
1907assert.ok(false);
1908// AssertionError: The expression evaluated to a falsy value:
1909//
1910//   assert.ok(false)
1911
1912assert.ok(0);
1913// AssertionError: The expression evaluated to a falsy value:
1914//
1915//   assert.ok(0)
1916```
1917
1918```cjs
1919const assert = require('node:assert/strict');
1920
1921assert.ok(true);
1922// OK
1923assert.ok(1);
1924// OK
1925
1926assert.ok();
1927// AssertionError: No value argument passed to `assert.ok()`
1928
1929assert.ok(false, 'it\'s false');
1930// AssertionError: it's false
1931
1932// In the repl:
1933assert.ok(typeof 123 === 'string');
1934// AssertionError: false == true
1935
1936// In a file (e.g. test.js):
1937assert.ok(typeof 123 === 'string');
1938// AssertionError: The expression evaluated to a falsy value:
1939//
1940//   assert.ok(typeof 123 === 'string')
1941
1942assert.ok(false);
1943// AssertionError: The expression evaluated to a falsy value:
1944//
1945//   assert.ok(false)
1946
1947assert.ok(0);
1948// AssertionError: The expression evaluated to a falsy value:
1949//
1950//   assert.ok(0)
1951```
1952
1953```mjs
1954import assert from 'node:assert/strict';
1955
1956// Using `assert()` works the same:
1957assert(0);
1958// AssertionError: The expression evaluated to a falsy value:
1959//
1960//   assert(0)
1961```
1962
1963```cjs
1964const assert = require('node:assert');
1965
1966// Using `assert()` works the same:
1967assert(0);
1968// AssertionError: The expression evaluated to a falsy value:
1969//
1970//   assert(0)
1971```
1972
1973## `assert.rejects(asyncFn[, error][, message])`
1974
1975<!-- YAML
1976added: v10.0.0
1977-->
1978
1979* `asyncFn` {Function|Promise}
1980* `error` {RegExp|Function|Object|Error}
1981* `message` {string}
1982
1983Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
1984calls the function and awaits the returned promise to complete. It will then
1985check that the promise is rejected.
1986
1987If `asyncFn` is a function and it throws an error synchronously,
1988`assert.rejects()` will return a rejected `Promise` with that error. If the
1989function does not return a promise, `assert.rejects()` will return a rejected
1990`Promise` with an [`ERR_INVALID_RETURN_VALUE`][] error. In both cases the error
1991handler is skipped.
1992
1993Besides the async nature to await the completion behaves identically to
1994[`assert.throws()`][].
1995
1996If specified, `error` can be a [`Class`][], [`RegExp`][], a validation function,
1997an object where each property will be tested for, or an instance of error where
1998each property will be tested for including the non-enumerable `message` and
1999`name` properties.
2000
2001If specified, `message` will be the message provided by the [`AssertionError`][]
2002if the `asyncFn` fails to reject.
2003
2004```mjs
2005import assert from 'node:assert/strict';
2006
2007await assert.rejects(
2008  async () => {
2009    throw new TypeError('Wrong value');
2010  },
2011  {
2012    name: 'TypeError',
2013    message: 'Wrong value',
2014  },
2015);
2016```
2017
2018```cjs
2019const assert = require('node:assert/strict');
2020
2021(async () => {
2022  await assert.rejects(
2023    async () => {
2024      throw new TypeError('Wrong value');
2025    },
2026    {
2027      name: 'TypeError',
2028      message: 'Wrong value',
2029    },
2030  );
2031})();
2032```
2033
2034```mjs
2035import assert from 'node:assert/strict';
2036
2037await assert.rejects(
2038  async () => {
2039    throw new TypeError('Wrong value');
2040  },
2041  (err) => {
2042    assert.strictEqual(err.name, 'TypeError');
2043    assert.strictEqual(err.message, 'Wrong value');
2044    return true;
2045  },
2046);
2047```
2048
2049```cjs
2050const assert = require('node:assert/strict');
2051
2052(async () => {
2053  await assert.rejects(
2054    async () => {
2055      throw new TypeError('Wrong value');
2056    },
2057    (err) => {
2058      assert.strictEqual(err.name, 'TypeError');
2059      assert.strictEqual(err.message, 'Wrong value');
2060      return true;
2061    },
2062  );
2063})();
2064```
2065
2066```mjs
2067import assert from 'node:assert/strict';
2068
2069assert.rejects(
2070  Promise.reject(new Error('Wrong value')),
2071  Error,
2072).then(() => {
2073  // ...
2074});
2075```
2076
2077```cjs
2078const assert = require('node:assert/strict');
2079
2080assert.rejects(
2081  Promise.reject(new Error('Wrong value')),
2082  Error,
2083).then(() => {
2084  // ...
2085});
2086```
2087
2088`error` cannot be a string. If a string is provided as the second
2089argument, then `error` is assumed to be omitted and the string will be used for
2090`message` instead. This can lead to easy-to-miss mistakes. Please read the
2091example in [`assert.throws()`][] carefully if using a string as the second
2092argument gets considered.
2093
2094## `assert.strictEqual(actual, expected[, message])`
2095
2096<!-- YAML
2097added: v0.1.21
2098changes:
2099  - version: v10.0.0
2100    pr-url: https://github.com/nodejs/node/pull/17003
2101    description: Used comparison changed from Strict Equality to `Object.is()`.
2102-->
2103
2104* `actual` {any}
2105* `expected` {any}
2106* `message` {string|Error}
2107
2108Tests strict equality between the `actual` and `expected` parameters as
2109determined by [`Object.is()`][].
2110
2111```mjs
2112import assert from 'node:assert/strict';
2113
2114assert.strictEqual(1, 2);
2115// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
2116//
2117// 1 !== 2
2118
2119assert.strictEqual(1, 1);
2120// OK
2121
2122assert.strictEqual('Hello foobar', 'Hello World!');
2123// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
2124// + actual - expected
2125//
2126// + 'Hello foobar'
2127// - 'Hello World!'
2128//          ^
2129
2130const apples = 1;
2131const oranges = 2;
2132assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
2133// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
2134
2135assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
2136// TypeError: Inputs are not identical
2137```
2138
2139```cjs
2140const assert = require('node:assert/strict');
2141
2142assert.strictEqual(1, 2);
2143// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
2144//
2145// 1 !== 2
2146
2147assert.strictEqual(1, 1);
2148// OK
2149
2150assert.strictEqual('Hello foobar', 'Hello World!');
2151// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
2152// + actual - expected
2153//
2154// + 'Hello foobar'
2155// - 'Hello World!'
2156//          ^
2157
2158const apples = 1;
2159const oranges = 2;
2160assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
2161// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
2162
2163assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
2164// TypeError: Inputs are not identical
2165```
2166
2167If the values are not strictly equal, an [`AssertionError`][] is thrown with a
2168`message` property set equal to the value of the `message` parameter. If the
2169`message` parameter is undefined, a default error message is assigned. If the
2170`message` parameter is an instance of an [`Error`][] then it will be thrown
2171instead of the [`AssertionError`][].
2172
2173## `assert.throws(fn[, error][, message])`
2174
2175<!-- YAML
2176added: v0.1.21
2177changes:
2178  - version: v10.2.0
2179    pr-url: https://github.com/nodejs/node/pull/20485
2180    description: The `error` parameter can be an object containing regular
2181                 expressions now.
2182  - version: v9.9.0
2183    pr-url: https://github.com/nodejs/node/pull/17584
2184    description: The `error` parameter can now be an object as well.
2185  - version: v4.2.0
2186    pr-url: https://github.com/nodejs/node/pull/3276
2187    description: The `error` parameter can now be an arrow function.
2188-->
2189
2190* `fn` {Function}
2191* `error` {RegExp|Function|Object|Error}
2192* `message` {string}
2193
2194Expects the function `fn` to throw an error.
2195
2196If specified, `error` can be a [`Class`][], [`RegExp`][], a validation function,
2197a validation object where each property will be tested for strict deep equality,
2198or an instance of error where each property will be tested for strict deep
2199equality including the non-enumerable `message` and `name` properties. When
2200using an object, it is also possible to use a regular expression, when
2201validating against a string property. See below for examples.
2202
2203If specified, `message` will be appended to the message provided by the
2204`AssertionError` if the `fn` call fails to throw or in case the error validation
2205fails.
2206
2207Custom validation object/error instance:
2208
2209```mjs
2210import assert from 'node:assert/strict';
2211
2212const err = new TypeError('Wrong value');
2213err.code = 404;
2214err.foo = 'bar';
2215err.info = {
2216  nested: true,
2217  baz: 'text',
2218};
2219err.reg = /abc/i;
2220
2221assert.throws(
2222  () => {
2223    throw err;
2224  },
2225  {
2226    name: 'TypeError',
2227    message: 'Wrong value',
2228    info: {
2229      nested: true,
2230      baz: 'text',
2231    },
2232    // Only properties on the validation object will be tested for.
2233    // Using nested objects requires all properties to be present. Otherwise
2234    // the validation is going to fail.
2235  },
2236);
2237
2238// Using regular expressions to validate error properties:
2239assert.throws(
2240  () => {
2241    throw err;
2242  },
2243  {
2244    // The `name` and `message` properties are strings and using regular
2245    // expressions on those will match against the string. If they fail, an
2246    // error is thrown.
2247    name: /^TypeError$/,
2248    message: /Wrong/,
2249    foo: 'bar',
2250    info: {
2251      nested: true,
2252      // It is not possible to use regular expressions for nested properties!
2253      baz: 'text',
2254    },
2255    // The `reg` property contains a regular expression and only if the
2256    // validation object contains an identical regular expression, it is going
2257    // to pass.
2258    reg: /abc/i,
2259  },
2260);
2261
2262// Fails due to the different `message` and `name` properties:
2263assert.throws(
2264  () => {
2265    const otherErr = new Error('Not found');
2266    // Copy all enumerable properties from `err` to `otherErr`.
2267    for (const [key, value] of Object.entries(err)) {
2268      otherErr[key] = value;
2269    }
2270    throw otherErr;
2271  },
2272  // The error's `message` and `name` properties will also be checked when using
2273  // an error as validation object.
2274  err,
2275);
2276```
2277
2278```cjs
2279const assert = require('node:assert/strict');
2280
2281const err = new TypeError('Wrong value');
2282err.code = 404;
2283err.foo = 'bar';
2284err.info = {
2285  nested: true,
2286  baz: 'text',
2287};
2288err.reg = /abc/i;
2289
2290assert.throws(
2291  () => {
2292    throw err;
2293  },
2294  {
2295    name: 'TypeError',
2296    message: 'Wrong value',
2297    info: {
2298      nested: true,
2299      baz: 'text',
2300    },
2301    // Only properties on the validation object will be tested for.
2302    // Using nested objects requires all properties to be present. Otherwise
2303    // the validation is going to fail.
2304  },
2305);
2306
2307// Using regular expressions to validate error properties:
2308assert.throws(
2309  () => {
2310    throw err;
2311  },
2312  {
2313    // The `name` and `message` properties are strings and using regular
2314    // expressions on those will match against the string. If they fail, an
2315    // error is thrown.
2316    name: /^TypeError$/,
2317    message: /Wrong/,
2318    foo: 'bar',
2319    info: {
2320      nested: true,
2321      // It is not possible to use regular expressions for nested properties!
2322      baz: 'text',
2323    },
2324    // The `reg` property contains a regular expression and only if the
2325    // validation object contains an identical regular expression, it is going
2326    // to pass.
2327    reg: /abc/i,
2328  },
2329);
2330
2331// Fails due to the different `message` and `name` properties:
2332assert.throws(
2333  () => {
2334    const otherErr = new Error('Not found');
2335    // Copy all enumerable properties from `err` to `otherErr`.
2336    for (const [key, value] of Object.entries(err)) {
2337      otherErr[key] = value;
2338    }
2339    throw otherErr;
2340  },
2341  // The error's `message` and `name` properties will also be checked when using
2342  // an error as validation object.
2343  err,
2344);
2345```
2346
2347Validate instanceof using constructor:
2348
2349```mjs
2350import assert from 'node:assert/strict';
2351
2352assert.throws(
2353  () => {
2354    throw new Error('Wrong value');
2355  },
2356  Error,
2357);
2358```
2359
2360```cjs
2361const assert = require('node:assert/strict');
2362
2363assert.throws(
2364  () => {
2365    throw new Error('Wrong value');
2366  },
2367  Error,
2368);
2369```
2370
2371Validate error message using [`RegExp`][]:
2372
2373Using a regular expression runs `.toString` on the error object, and will
2374therefore also include the error name.
2375
2376```mjs
2377import assert from 'node:assert/strict';
2378
2379assert.throws(
2380  () => {
2381    throw new Error('Wrong value');
2382  },
2383  /^Error: Wrong value$/,
2384);
2385```
2386
2387```cjs
2388const assert = require('node:assert/strict');
2389
2390assert.throws(
2391  () => {
2392    throw new Error('Wrong value');
2393  },
2394  /^Error: Wrong value$/,
2395);
2396```
2397
2398Custom error validation:
2399
2400The function must return `true` to indicate all internal validations passed.
2401It will otherwise fail with an [`AssertionError`][].
2402
2403```mjs
2404import assert from 'node:assert/strict';
2405
2406assert.throws(
2407  () => {
2408    throw new Error('Wrong value');
2409  },
2410  (err) => {
2411    assert(err instanceof Error);
2412    assert(/value/.test(err));
2413    // Avoid returning anything from validation functions besides `true`.
2414    // Otherwise, it's not clear what part of the validation failed. Instead,
2415    // throw an error about the specific validation that failed (as done in this
2416    // example) and add as much helpful debugging information to that error as
2417    // possible.
2418    return true;
2419  },
2420  'unexpected error',
2421);
2422```
2423
2424```cjs
2425const assert = require('node:assert/strict');
2426
2427assert.throws(
2428  () => {
2429    throw new Error('Wrong value');
2430  },
2431  (err) => {
2432    assert(err instanceof Error);
2433    assert(/value/.test(err));
2434    // Avoid returning anything from validation functions besides `true`.
2435    // Otherwise, it's not clear what part of the validation failed. Instead,
2436    // throw an error about the specific validation that failed (as done in this
2437    // example) and add as much helpful debugging information to that error as
2438    // possible.
2439    return true;
2440  },
2441  'unexpected error',
2442);
2443```
2444
2445`error` cannot be a string. If a string is provided as the second
2446argument, then `error` is assumed to be omitted and the string will be used for
2447`message` instead. This can lead to easy-to-miss mistakes. Using the same
2448message as the thrown error message is going to result in an
2449`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using
2450a string as the second argument gets considered:
2451
2452```mjs
2453import assert from 'node:assert/strict';
2454
2455function throwingFirst() {
2456  throw new Error('First');
2457}
2458
2459function throwingSecond() {
2460  throw new Error('Second');
2461}
2462
2463function notThrowing() {}
2464
2465// The second argument is a string and the input function threw an Error.
2466// The first case will not throw as it does not match for the error message
2467// thrown by the input function!
2468assert.throws(throwingFirst, 'Second');
2469// In the next example the message has no benefit over the message from the
2470// error and since it is not clear if the user intended to actually match
2471// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
2472assert.throws(throwingSecond, 'Second');
2473// TypeError [ERR_AMBIGUOUS_ARGUMENT]
2474
2475// The string is only used (as message) in case the function does not throw:
2476assert.throws(notThrowing, 'Second');
2477// AssertionError [ERR_ASSERTION]: Missing expected exception: Second
2478
2479// If it was intended to match for the error message do this instead:
2480// It does not throw because the error messages match.
2481assert.throws(throwingSecond, /Second$/);
2482
2483// If the error message does not match, an AssertionError is thrown.
2484assert.throws(throwingFirst, /Second$/);
2485// AssertionError [ERR_ASSERTION]
2486```
2487
2488```cjs
2489const assert = require('node:assert/strict');
2490
2491function throwingFirst() {
2492  throw new Error('First');
2493}
2494
2495function throwingSecond() {
2496  throw new Error('Second');
2497}
2498
2499function notThrowing() {}
2500
2501// The second argument is a string and the input function threw an Error.
2502// The first case will not throw as it does not match for the error message
2503// thrown by the input function!
2504assert.throws(throwingFirst, 'Second');
2505// In the next example the message has no benefit over the message from the
2506// error and since it is not clear if the user intended to actually match
2507// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
2508assert.throws(throwingSecond, 'Second');
2509// TypeError [ERR_AMBIGUOUS_ARGUMENT]
2510
2511// The string is only used (as message) in case the function does not throw:
2512assert.throws(notThrowing, 'Second');
2513// AssertionError [ERR_ASSERTION]: Missing expected exception: Second
2514
2515// If it was intended to match for the error message do this instead:
2516// It does not throw because the error messages match.
2517assert.throws(throwingSecond, /Second$/);
2518
2519// If the error message does not match, an AssertionError is thrown.
2520assert.throws(throwingFirst, /Second$/);
2521// AssertionError [ERR_ASSERTION]
2522```
2523
2524Due to the confusing error-prone notation, avoid a string as the second
2525argument.
2526
2527[Object wrappers]: https://developer.mozilla.org/en-US/docs/Glossary/Primitive#Primitive_wrapper_objects_in_JavaScript
2528[Object.prototype.toString()]: https://tc39.github.io/ecma262/#sec-object.prototype.tostring
2529[`!=` operator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality
2530[`===` operator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality
2531[`==` operator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality
2532[`AssertionError`]: #class-assertassertionerror
2533[`CallTracker`]: #class-assertcalltracker
2534[`Class`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
2535[`ERR_INVALID_RETURN_VALUE`]: errors.md#err_invalid_return_value
2536[`Error.captureStackTrace`]: errors.md#errorcapturestacktracetargetobject-constructoropt
2537[`Error`]: errors.md#class-error
2538[`Map`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
2539[`Object.is()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
2540[`RegExp`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
2541[`Set`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
2542[`Symbol`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol
2543[`TypeError`]: errors.md#class-typeerror
2544[`WeakMap`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap
2545[`WeakSet`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet
2546[`assert.deepEqual()`]: #assertdeepequalactual-expected-message
2547[`assert.deepStrictEqual()`]: #assertdeepstrictequalactual-expected-message
2548[`assert.doesNotThrow()`]: #assertdoesnotthrowfn-error-message
2549[`assert.equal()`]: #assertequalactual-expected-message
2550[`assert.notDeepEqual()`]: #assertnotdeepequalactual-expected-message
2551[`assert.notDeepStrictEqual()`]: #assertnotdeepstrictequalactual-expected-message
2552[`assert.notEqual()`]: #assertnotequalactual-expected-message
2553[`assert.notStrictEqual()`]: #assertnotstrictequalactual-expected-message
2554[`assert.ok()`]: #assertokvalue-message
2555[`assert.strictEqual()`]: #assertstrictequalactual-expected-message
2556[`assert.throws()`]: #assertthrowsfn-error-message
2557[`getColorDepth()`]: tty.md#writestreamgetcolordepthenv
2558[`process.on('exit')`]: process.md#event-exit
2559[`tracker.calls()`]: #trackercallsfn-exact
2560[`tracker.verify()`]: #trackerverify
2561[enumerable "own" properties]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties
2562[prototype-spec]: https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots
2563