• 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 `assert` module provides a set of assertion functions for verifying
10invariants.
11
12## Strict assertion mode
13<!-- YAML
14added: v9.9.0
15changes:
16  - version:
17      - v13.9.0
18      - v12.16.2
19    pr-url: https://github.com/nodejs/node/pull/31635
20    description: Changed "strict mode" to "strict assertion mode" and "legacy
21                 mode" to "legacy assertion mode" to avoid confusion with the
22                 more usual meaning of "strict mode".
23  - version: v9.9.0
24    pr-url: https://github.com/nodejs/node/pull/17615
25    description: Added error diffs to the strict assertion mode.
26  - version: v9.9.0
27    pr-url: https://github.com/nodejs/node/pull/17002
28    description: Added strict assertion mode to the assert module.
29-->
30
31In strict assertion mode, non-strict methods behave like their corresponding
32strict methods. For example, [`assert.deepEqual()`][] will behave like
33[`assert.deepStrictEqual()`][].
34
35In strict assertion mode, error messages for objects display a diff. In legacy
36assertion mode, error messages for objects display the objects, often truncated.
37
38To use strict assertion mode:
39
40```js
41const assert = require('assert').strict;
42```
43
44Example error diff:
45
46```js
47const assert = require('assert').strict;
48
49assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
50// AssertionError: Expected inputs to be strictly deep-equal:
51// + actual - expected ... Lines skipped
52//
53//   [
54//     [
55// ...
56//       2,
57// +     3
58// -     '3'
59//     ],
60// ...
61//     5
62//   ]
63```
64
65To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS`
66environment variables. This will also deactivate the colors in the REPL. For
67more on color support in terminal environments, read the tty
68[getColorDepth()](tty.md#tty_writestream_getcolordepth_env) documentation.
69
70## Legacy assertion mode
71
72Legacy assertion mode uses the [Abstract Equality Comparison][] in:
73
74* [`assert.deepEqual()`][]
75* [`assert.equal()`][]
76* [`assert.notDeepEqual()`][]
77* [`assert.notEqual()`][]
78
79To use legacy assertion mode:
80
81```js
82const assert = require('assert');
83```
84
85Whenever possible, use the [strict assertion mode][] instead. Otherwise, the
86[Abstract Equality Comparison][] may cause surprising results. This is
87especially true for [`assert.deepEqual()`][], where the comparison rules are
88lax:
89
90```js
91// WARNING: This does not throw an AssertionError!
92assert.deepEqual(/a/gi, new Date());
93```
94
95## Class: assert.AssertionError
96
97* Extends: {errors.Error}
98
99Indicates the failure of an assertion. All errors thrown by the `assert` module
100will be instances of the `AssertionError` class.
101
102### `new assert.AssertionError(options)`
103<!-- YAML
104added: v0.1.21
105-->
106
107* `options` {Object}
108  * `message` {string} If provided, the error message is set to this value.
109  * `actual` {any} The `actual` property on the error instance.
110  * `expected` {any} The `expected` property on the error instance.
111  * `operator` {string} The `operator` property on the error instance.
112  * `stackStartFn` {Function} If provided, the generated stack trace omits
113    frames before this function.
114
115A subclass of `Error` that indicates the failure of an assertion.
116
117All instances contain the built-in `Error` properties (`message` and `name`)
118and:
119
120* `actual` {any} Set to the `actual` argument for methods such as
121  [`assert.strictEqual()`][].
122* `expected` {any} Set to the `expected` value for methods such as
123  [`assert.strictEqual()`][].
124* `generatedMessage` {boolean} Indicates if the message was auto-generated
125  (`true`) or not.
126* `code` {string} Value is always `ERR_ASSERTION` to show that the error is an
127  assertion error.
128* `operator` {string} Set to the passed in operator value.
129
130```js
131const assert = require('assert');
132
133// Generate an AssertionError to compare the error message later:
134const { message } = new assert.AssertionError({
135  actual: 1,
136  expected: 2,
137  operator: 'strictEqual'
138});
139
140// Verify error output:
141try {
142  assert.strictEqual(1, 2);
143} catch (err) {
144  assert(err instanceof assert.AssertionError);
145  assert.strictEqual(err.message, message);
146  assert.strictEqual(err.name, 'AssertionError');
147  assert.strictEqual(err.actual, 1);
148  assert.strictEqual(err.expected, 2);
149  assert.strictEqual(err.code, 'ERR_ASSERTION');
150  assert.strictEqual(err.operator, 'strictEqual');
151  assert.strictEqual(err.generatedMessage, true);
152}
153```
154
155## Class: `assert.CallTracker`
156<!-- YAML
157added: v14.2.0
158-->
159
160> Stability: 1 - Experimental
161
162This feature is currently experimental and behavior might still change.
163
164### `new assert.CallTracker()`
165<!-- YAML
166added: v14.2.0
167-->
168
169Creates a new [`CallTracker`][] object which can be used to track if functions
170were called a specific number of times. The `tracker.verify()` must be called
171for the verification to take place. The usual pattern would be to call it in a
172[`process.on('exit')`][] handler.
173
174```js
175const assert = require('assert');
176
177const tracker = new assert.CallTracker();
178
179function func() {}
180
181// callsfunc() must be called exactly 1 time before tracker.verify().
182const callsfunc = tracker.calls(func, 1);
183
184callsfunc();
185
186// Calls tracker.verify() and verifies if all tracker.calls() functions have
187// been called exact times.
188process.on('exit', () => {
189  tracker.verify();
190});
191```
192
193### `tracker.calls([fn][, exact])`
194<!-- YAML
195added: v14.2.0
196-->
197
198* `fn` {Function} **Default** A no-op function.
199* `exact` {number} **Default** `1`.
200* Returns: {Function} that wraps `fn`.
201
202The wrapper function is expected to be called exactly `exact` times. If the
203function has not been called exactly `exact` times when
204[`tracker.verify()`][] is called, then [`tracker.verify()`][] will throw an
205error.
206
207```js
208const assert = require('assert');
209
210// Creates call tracker.
211const tracker = new assert.CallTracker();
212
213function func() {}
214
215// Returns a function that wraps func() that must be called exact times
216// before tracker.verify().
217const callsfunc = tracker.calls(func);
218```
219
220### `tracker.report()`
221<!-- YAML
222added: v14.2.0
223-->
224
225* Returns: {Array} of objects containing information about the wrapper functions
226  returned by [`tracker.calls()`][].
227* Object {Object}
228  * `message` {string}
229  * `actual` {number} The actual number of times the function was called.
230  * `expected` {number} The number of times the function was expected to be
231    called.
232  * `operator` {string} The name of the function that is wrapped.
233  * `stack` {Object} A stack trace of the function.
234
235The arrays contains information about the expected and actual number of calls of
236the functions that have not been called the expected number of times.
237
238```js
239const assert = require('assert');
240
241// Creates call tracker.
242const tracker = new assert.CallTracker();
243
244function func() {}
245
246function foo() {}
247
248// Returns a function that wraps func() that must be called exact times
249// before tracker.verify().
250const callsfunc = tracker.calls(func, 2);
251
252// Returns an array containing information on callsfunc()
253tracker.report();
254// [
255//  {
256//    message: 'Expected the func function to be executed 2 time(s) but was
257//    executed 0 time(s).',
258//    actual: 0,
259//    expected: 2,
260//    operator: 'func',
261//    stack: stack trace
262//  }
263// ]
264```
265
266### `tracker.verify()`
267<!-- YAML
268added: v14.2.0
269-->
270
271Iterates through the list of functions passed to
272[`tracker.calls()`][] and will throw an error for functions that
273have not been called the expected number of times.
274
275```js
276const assert = require('assert');
277
278// Creates call tracker.
279const tracker = new assert.CallTracker();
280
281function func() {}
282
283// Returns a function that wraps func() that must be called exact times
284// before tracker.verify().
285const callsfunc = tracker.calls(func, 2);
286
287callsfunc();
288
289// Will throw an error since callsfunc() was only called once.
290tracker.verify();
291```
292
293## `assert(value[, message])`
294<!-- YAML
295added: v0.5.9
296-->
297
298* `value` {any} The input that is checked for being truthy.
299* `message` {string|Error}
300
301An alias of [`assert.ok()`][].
302
303## `assert.deepEqual(actual, expected[, message])`
304<!-- YAML
305added: v0.1.21
306changes:
307  - version: v14.18.0
308    pr-url: https://github.com/nodejs/node/pull/38113
309    description: In Legacy assertion mode, changed status from Deprecated to
310                 Legacy.
311  - version: v14.0.0
312    pr-url: https://github.com/nodejs/node/pull/30766
313    description: NaN is now treated as being identical in case both sides are
314                 NaN.
315  - version: v12.0.0
316    pr-url: https://github.com/nodejs/node/pull/25008
317    description: The type tags are now properly compared and there are a couple
318                 minor comparison adjustments to make the check less surprising.
319  - version: v9.0.0
320    pr-url: https://github.com/nodejs/node/pull/15001
321    description: The `Error` names and messages are now properly compared.
322  - version: v8.0.0
323    pr-url: https://github.com/nodejs/node/pull/12142
324    description: The `Set` and `Map` content is also compared.
325  - version:
326    - v6.4.0
327    - v4.7.1
328    pr-url: https://github.com/nodejs/node/pull/8002
329    description: Typed array slices are handled correctly now.
330  - version:
331    - v6.1.0
332    - v4.5.0
333    pr-url: https://github.com/nodejs/node/pull/6432
334    description: Objects with circular references can be used as inputs now.
335  - version:
336    - v5.10.1
337    - v4.4.3
338    pr-url: https://github.com/nodejs/node/pull/5910
339    description: Handle non-`Uint8Array` typed arrays correctly.
340-->
341
342* `actual` {any}
343* `expected` {any}
344* `message` {string|Error}
345
346**Strict assertion mode**
347
348An alias of [`assert.deepStrictEqual()`][].
349
350**Legacy assertion mode**
351
352> Stability: 3 - Legacy: Use [`assert.deepStrictEqual()`][] instead.
353
354Tests for deep equality between the `actual` and `expected` parameters. Consider
355using [`assert.deepStrictEqual()`][] instead. [`assert.deepEqual()`][] can have
356surprising results.
357
358_Deep equality_ means that the enumerable "own" properties of child objects
359are also recursively evaluated by the following rules.
360
361### Comparison details
362
363* Primitive values are compared with the [Abstract Equality Comparison][]
364  ( `==` ) with the exception of `NaN`. It is treated as being identical in case
365  both sides are `NaN`.
366* [Type tags][Object.prototype.toString()] of objects should be the same.
367* Only [enumerable "own" properties][] are considered.
368* [`Error`][] names and messages are always compared, even if these are not
369  enumerable properties.
370* [Object wrappers][] are compared both as objects and unwrapped values.
371* `Object` properties are compared unordered.
372* [`Map`][] keys and [`Set`][] items are compared unordered.
373* Recursion stops when both sides differ or both sides encounter a circular
374  reference.
375* Implementation does not test the [`[[Prototype]]`][prototype-spec] of
376  objects.
377* [`Symbol`][] properties are not compared.
378* [`WeakMap`][] and [`WeakSet`][] comparison does not rely on their values.
379
380The following example does not throw an [`AssertionError`][] because the
381primitives are considered equal by the [Abstract Equality Comparison][]
382( `==` ).
383
384```js
385// WARNING: This does not throw an AssertionError!
386assert.deepEqual('+00000000', false);
387```
388
389"Deep" equality means that the enumerable "own" properties of child objects
390are evaluated also:
391
392```js
393const assert = require('assert');
394
395const obj1 = {
396  a: {
397    b: 1
398  }
399};
400const obj2 = {
401  a: {
402    b: 2
403  }
404};
405const obj3 = {
406  a: {
407    b: 1
408  }
409};
410const obj4 = Object.create(obj1);
411
412assert.deepEqual(obj1, obj1);
413// OK
414
415// Values of b are different:
416assert.deepEqual(obj1, obj2);
417// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
418
419assert.deepEqual(obj1, obj3);
420// OK
421
422// Prototypes are ignored:
423assert.deepEqual(obj1, obj4);
424// AssertionError: { a: { b: 1 } } deepEqual {}
425```
426
427If the values are not equal, an [`AssertionError`][] is thrown with a `message`
428property set equal to the value of the `message` parameter. If the `message`
429parameter is undefined, a default error message is assigned. If the `message`
430parameter is an instance of an [`Error`][] then it will be thrown instead of the
431[`AssertionError`][].
432
433## `assert.deepStrictEqual(actual, expected[, message])`
434<!-- YAML
435added: v1.2.0
436changes:
437  - version: v9.0.0
438    pr-url: https://github.com/nodejs/node/pull/15169
439    description: Enumerable symbol properties are now compared.
440  - version: v9.0.0
441    pr-url: https://github.com/nodejs/node/pull/15036
442    description: The `NaN` is now compared using the
443              [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero)
444              comparison.
445  - version: v8.5.0
446    pr-url: https://github.com/nodejs/node/pull/15001
447    description: The `Error` names and messages are now properly compared.
448  - version: v8.0.0
449    pr-url: https://github.com/nodejs/node/pull/12142
450    description: The `Set` and `Map` content is also compared.
451  - version:
452    - v6.4.0
453    - v4.7.1
454    pr-url: https://github.com/nodejs/node/pull/8002
455    description: Typed array slices are handled correctly now.
456  - version: v6.1.0
457    pr-url: https://github.com/nodejs/node/pull/6432
458    description: Objects with circular references can be used as inputs now.
459  - version:
460    - v5.10.1
461    - v4.4.3
462    pr-url: https://github.com/nodejs/node/pull/5910
463    description: Handle non-`Uint8Array` typed arrays correctly.
464-->
465
466* `actual` {any}
467* `expected` {any}
468* `message` {string|Error}
469
470Tests for deep equality between the `actual` and `expected` parameters.
471"Deep" equality means that the enumerable "own" properties of child objects
472are recursively evaluated also by the following rules.
473
474### Comparison details
475
476* Primitive values are compared using the [SameValue Comparison][], used by
477  [`Object.is()`][].
478* [Type tags][Object.prototype.toString()] of objects should be the same.
479* [`[[Prototype]]`][prototype-spec] of objects are compared using
480  the [Strict Equality Comparison][].
481* Only [enumerable "own" properties][] are considered.
482* [`Error`][] names and messages are always compared, even if these are not
483  enumerable properties.
484* Enumerable own [`Symbol`][] properties are compared as well.
485* [Object wrappers][] are compared both as objects and unwrapped values.
486* `Object` properties are compared unordered.
487* [`Map`][] keys and [`Set`][] items are compared unordered.
488* Recursion stops when both sides differ or both sides encounter a circular
489  reference.
490* [`WeakMap`][] and [`WeakSet`][] comparison does not rely on their values. See
491  below for further details.
492
493```js
494const assert = require('assert').strict;
495
496// This fails because 1 !== '1'.
497assert.deepStrictEqual({ a: 1 }, { a: '1' });
498// AssertionError: Expected inputs to be strictly deep-equal:
499// + actual - expected
500//
501//   {
502// +   a: 1
503// -   a: '1'
504//   }
505
506// The following objects don't have own properties
507const date = new Date();
508const object = {};
509const fakeDate = {};
510Object.setPrototypeOf(fakeDate, Date.prototype);
511
512// Different [[Prototype]]:
513assert.deepStrictEqual(object, fakeDate);
514// AssertionError: Expected inputs to be strictly deep-equal:
515// + actual - expected
516//
517// + {}
518// - Date {}
519
520// Different type tags:
521assert.deepStrictEqual(date, fakeDate);
522// AssertionError: Expected inputs to be strictly deep-equal:
523// + actual - expected
524//
525// + 2018-04-26T00:49:08.604Z
526// - Date {}
527
528assert.deepStrictEqual(NaN, NaN);
529// OK, because of the SameValue comparison
530
531// Different unwrapped numbers:
532assert.deepStrictEqual(new Number(1), new Number(2));
533// AssertionError: Expected inputs to be strictly deep-equal:
534// + actual - expected
535//
536// + [Number: 1]
537// - [Number: 2]
538
539assert.deepStrictEqual(new String('foo'), Object('foo'));
540// OK because the object and the string are identical when unwrapped.
541
542assert.deepStrictEqual(-0, -0);
543// OK
544
545// Different zeros using the SameValue Comparison:
546assert.deepStrictEqual(0, -0);
547// AssertionError: Expected inputs to be strictly deep-equal:
548// + actual - expected
549//
550// + 0
551// - -0
552
553const symbol1 = Symbol();
554const symbol2 = Symbol();
555assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
556// OK, because it is the same symbol on both objects.
557
558assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
559// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:
560//
561// {
562//   [Symbol()]: 1
563// }
564
565const weakMap1 = new WeakMap();
566const weakMap2 = new WeakMap([[{}, {}]]);
567const weakMap3 = new WeakMap();
568weakMap3.unequal = true;
569
570assert.deepStrictEqual(weakMap1, weakMap2);
571// OK, because it is impossible to compare the entries
572
573// Fails because weakMap3 has a property that weakMap1 does not contain:
574assert.deepStrictEqual(weakMap1, weakMap3);
575// AssertionError: Expected inputs to be strictly deep-equal:
576// + actual - expected
577//
578//   WeakMap {
579// +   [items unknown]
580// -   [items unknown],
581// -   unequal: true
582//   }
583```
584
585If the values are not equal, an [`AssertionError`][] is thrown with a `message`
586property set equal to the value of the `message` parameter. If the `message`
587parameter is undefined, a default error message is assigned. If the `message`
588parameter is an instance of an [`Error`][] then it will be thrown instead of the
589`AssertionError`.
590
591## `assert.doesNotMatch(string, regexp[, message])`
592<!-- YAML
593added:
594  - v13.6.0
595  - v12.16.0
596-->
597
598* `string` {string}
599* `regexp` {RegExp}
600* `message` {string|Error}
601
602> Stability: 1 - Experimental
603
604Expects the `string` input not to match the regular expression.
605
606This feature is currently experimental and the name might change or it might be
607completely removed again.
608
609```js
610const assert = require('assert').strict;
611
612assert.doesNotMatch('I will fail', /fail/);
613// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
614
615assert.doesNotMatch(123, /pass/);
616// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
617
618assert.doesNotMatch('I will pass', /different/);
619// OK
620```
621
622If the values do match, or if the `string` argument is of another type than
623`string`, an [`AssertionError`][] is thrown with a `message` property set equal
624to the value of the `message` parameter. If the `message` parameter is
625undefined, a default error message is assigned. If the `message` parameter is an
626instance of an [`Error`][] then it will be thrown instead of the
627[`AssertionError`][].
628
629## `assert.doesNotReject(asyncFn[, error][, message])`
630<!-- YAML
631added: v10.0.0
632-->
633
634* `asyncFn` {Function|Promise}
635* `error` {RegExp|Function}
636* `message` {string}
637
638Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
639calls the function and awaits the returned promise to complete. It will then
640check that the promise is not rejected.
641
642If `asyncFn` is a function and it throws an error synchronously,
643`assert.doesNotReject()` will return a rejected `Promise` with that error. If
644the function does not return a promise, `assert.doesNotReject()` will return a
645rejected `Promise` with an [`ERR_INVALID_RETURN_VALUE`][] error. In both cases
646the error handler is skipped.
647
648Using `assert.doesNotReject()` is actually not useful because there is little
649benefit in catching a rejection and then rejecting it again. Instead, consider
650adding a comment next to the specific code path that should not reject and keep
651error messages as expressive as possible.
652
653If specified, `error` can be a [`Class`][], [`RegExp`][] or a validation
654function. See [`assert.throws()`][] for more details.
655
656Besides the async nature to await the completion behaves identically to
657[`assert.doesNotThrow()`][].
658
659<!-- eslint-disable no-restricted-syntax -->
660```js
661(async () => {
662  await assert.doesNotReject(
663    async () => {
664      throw new TypeError('Wrong value');
665    },
666    SyntaxError
667  );
668})();
669```
670
671<!-- eslint-disable no-restricted-syntax -->
672```js
673assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
674  .then(() => {
675    // ...
676  });
677```
678
679## `assert.doesNotThrow(fn[, error][, message])`
680<!-- YAML
681added: v0.1.21
682changes:
683  - version:
684    - v5.11.0
685    - v4.4.5
686    pr-url: https://github.com/nodejs/node/pull/2407
687    description: The `message` parameter is respected now.
688  - version: v4.2.0
689    pr-url: https://github.com/nodejs/node/pull/3276
690    description: The `error` parameter can now be an arrow function.
691-->
692
693* `fn` {Function}
694* `error` {RegExp|Function}
695* `message` {string}
696
697Asserts that the function `fn` does not throw an error.
698
699Using `assert.doesNotThrow()` is actually not useful because there
700is no benefit in catching an error and then rethrowing it. Instead, consider
701adding a comment next to the specific code path that should not throw and keep
702error messages as expressive as possible.
703
704When `assert.doesNotThrow()` is called, it will immediately call the `fn`
705function.
706
707If an error is thrown and it is the same type as that specified by the `error`
708parameter, then an [`AssertionError`][] is thrown. If the error is of a
709different type, or if the `error` parameter is undefined, the error is
710propagated back to the caller.
711
712If specified, `error` can be a [`Class`][], [`RegExp`][] or a validation
713function. See [`assert.throws()`][] for more details.
714
715The following, for instance, will throw the [`TypeError`][] because there is no
716matching error type in the assertion:
717
718<!-- eslint-disable no-restricted-syntax -->
719```js
720assert.doesNotThrow(
721  () => {
722    throw new TypeError('Wrong value');
723  },
724  SyntaxError
725);
726```
727
728However, the following will result in an [`AssertionError`][] with the message
729'Got unwanted exception...':
730
731<!-- eslint-disable no-restricted-syntax -->
732```js
733assert.doesNotThrow(
734  () => {
735    throw new TypeError('Wrong value');
736  },
737  TypeError
738);
739```
740
741If an [`AssertionError`][] is thrown and a value is provided for the `message`
742parameter, the value of `message` will be appended to the [`AssertionError`][]
743message:
744
745<!-- eslint-disable no-restricted-syntax -->
746```js
747assert.doesNotThrow(
748  () => {
749    throw new TypeError('Wrong value');
750  },
751  /Wrong value/,
752  'Whoops'
753);
754// Throws: AssertionError: Got unwanted exception: Whoops
755```
756
757## `assert.equal(actual, expected[, message])`
758<!-- YAML
759added: v0.1.21
760changes:
761  - version: v14.18.0
762    pr-url: https://github.com/nodejs/node/pull/38113
763    description: In Legacy assertion mode, changed status from Deprecated to
764                 Legacy.
765  - version: v14.0.0
766    pr-url: https://github.com/nodejs/node/pull/30766
767    description: NaN is now treated as being identical in case both sides are
768                 NaN.
769-->
770
771* `actual` {any}
772* `expected` {any}
773* `message` {string|Error}
774
775**Strict assertion mode**
776
777An alias of [`assert.strictEqual()`][].
778
779**Legacy assertion mode**
780
781> Stability: 3 - Legacy: Use [`assert.strictEqual()`][] instead.
782
783Tests shallow, coercive equality between the `actual` and `expected` parameters
784using the [Abstract Equality Comparison][] ( `==` ). `NaN` is special handled
785and treated as being identical in case both sides are `NaN`.
786
787```js
788const assert = require('assert');
789
790assert.equal(1, 1);
791// OK, 1 == 1
792assert.equal(1, '1');
793// OK, 1 == '1'
794assert.equal(NaN, NaN);
795// OK
796
797assert.equal(1, 2);
798// AssertionError: 1 == 2
799assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
800// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
801```
802
803If the values are not equal, an [`AssertionError`][] is thrown with a `message`
804property set equal to the value of the `message` parameter. If the `message`
805parameter is undefined, a default error message is assigned. If the `message`
806parameter is an instance of an [`Error`][] then it will be thrown instead of the
807`AssertionError`.
808
809## `assert.fail([message])`
810<!-- YAML
811added: v0.1.21
812-->
813
814* `message` {string|Error} **Default:** `'Failed'`
815
816Throws an [`AssertionError`][] with the provided error message or a default
817error message. If the `message` parameter is an instance of an [`Error`][] then
818it will be thrown instead of the [`AssertionError`][].
819
820```js
821const assert = require('assert').strict;
822
823assert.fail();
824// AssertionError [ERR_ASSERTION]: Failed
825
826assert.fail('boom');
827// AssertionError [ERR_ASSERTION]: boom
828
829assert.fail(new TypeError('need array'));
830// TypeError: need array
831```
832
833Using `assert.fail()` with more than two arguments is possible but deprecated.
834See below for further details.
835
836## `assert.fail(actual, expected[, message[, operator[, stackStartFn]]])`
837<!-- YAML
838added: v0.1.21
839changes:
840  - version: v10.0.0
841    pr-url: https://github.com/nodejs/node/pull/18418
842    description: Calling `assert.fail()` with more than one argument is
843                 deprecated and emits a warning.
844-->
845
846> Stability: 0 - Deprecated: Use `assert.fail([message])` or other assert
847> functions instead.
848
849* `actual` {any}
850* `expected` {any}
851* `message` {string|Error}
852* `operator` {string} **Default:** `'!='`
853* `stackStartFn` {Function} **Default:** `assert.fail`
854
855If `message` is falsy, the error message is set as the values of `actual` and
856`expected` separated by the provided `operator`. If just the two `actual` and
857`expected` arguments are provided, `operator` will default to `'!='`. If
858`message` is provided as third argument it will be used as the error message and
859the other arguments will be stored as properties on the thrown object. If
860`stackStartFn` is provided, all stack frames above that function will be
861removed from stacktrace (see [`Error.captureStackTrace`][]). If no arguments are
862given, the default message `Failed` will be used.
863
864```js
865const assert = require('assert').strict;
866
867assert.fail('a', 'b');
868// AssertionError [ERR_ASSERTION]: 'a' != 'b'
869
870assert.fail(1, 2, undefined, '>');
871// AssertionError [ERR_ASSERTION]: 1 > 2
872
873assert.fail(1, 2, 'fail');
874// AssertionError [ERR_ASSERTION]: fail
875
876assert.fail(1, 2, 'whoops', '>');
877// AssertionError [ERR_ASSERTION]: whoops
878
879assert.fail(1, 2, new TypeError('need array'));
880// TypeError: need array
881```
882
883In the last three cases `actual`, `expected`, and `operator` have no
884influence on the error message.
885
886Example use of `stackStartFn` for truncating the exception's stacktrace:
887
888```js
889function suppressFrame() {
890  assert.fail('a', 'b', undefined, '!==', suppressFrame);
891}
892suppressFrame();
893// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
894//     at repl:1:1
895//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)
896//     ...
897```
898
899## `assert.ifError(value)`
900<!-- YAML
901added: v0.1.97
902changes:
903  - version: v10.0.0
904    pr-url: https://github.com/nodejs/node/pull/18247
905    description: Instead of throwing the original error it is now wrapped into
906                 an [`AssertionError`][] that contains the full stack trace.
907  - version: v10.0.0
908    pr-url: https://github.com/nodejs/node/pull/18247
909    description: Value may now only be `undefined` or `null`. Before all falsy
910                 values were handled the same as `null` and did not throw.
911-->
912
913* `value` {any}
914
915Throws `value` if `value` is not `undefined` or `null`. This is useful when
916testing the `error` argument in callbacks. The stack trace contains all frames
917from the error passed to `ifError()` including the potential new frames for
918`ifError()` itself.
919
920```js
921const assert = require('assert').strict;
922
923assert.ifError(null);
924// OK
925assert.ifError(0);
926// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
927assert.ifError('error');
928// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
929assert.ifError(new Error());
930// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error
931
932// Create some random error frames.
933let err;
934(function errorFrame() {
935  err = new Error('test error');
936})();
937
938(function ifErrorFrame() {
939  assert.ifError(err);
940})();
941// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
942//     at ifErrorFrame
943//     at errorFrame
944```
945
946## `assert.match(string, regexp[, message])`
947<!-- YAML
948added:
949  - v13.6.0
950  - v12.16.0
951-->
952
953* `string` {string}
954* `regexp` {RegExp}
955* `message` {string|Error}
956
957> Stability: 1 - Experimental
958
959Expects the `string` input to match the regular expression.
960
961This feature is currently experimental and the name might change or it might be
962completely removed again.
963
964```js
965const assert = require('assert').strict;
966
967assert.match('I will fail', /pass/);
968// AssertionError [ERR_ASSERTION]: The input did not match the regular ...
969
970assert.match(123, /pass/);
971// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
972
973assert.match('I will pass', /pass/);
974// OK
975```
976
977If the values do not match, or if the `string` argument is of another type than
978`string`, an [`AssertionError`][] is thrown with a `message` property set equal
979to the value of the `message` parameter. If the `message` parameter is
980undefined, a default error message is assigned. If the `message` parameter is an
981instance of an [`Error`][] then it will be thrown instead of the
982[`AssertionError`][].
983
984## `assert.notDeepEqual(actual, expected[, message])`
985<!-- YAML
986added: v0.1.21
987changes:
988  - version: v14.18.0
989    pr-url: https://github.com/nodejs/node/pull/38113
990    description: In Legacy assertion mode, changed status from Deprecated to
991                 Legacy.
992  - version: v14.0.0
993    pr-url: https://github.com/nodejs/node/pull/30766
994    description: NaN is now treated as being identical in case both sides are
995                 NaN.
996  - version: v9.0.0
997    pr-url: https://github.com/nodejs/node/pull/15001
998    description: The `Error` names and messages are now properly compared.
999  - version: v8.0.0
1000    pr-url: https://github.com/nodejs/node/pull/12142
1001    description: The `Set` and `Map` content is also compared.
1002  - version:
1003    - v6.4.0
1004    - v4.7.1
1005    pr-url: https://github.com/nodejs/node/pull/8002
1006    description: Typed array slices are handled correctly now.
1007  - version:
1008    - v6.1.0
1009    - v4.5.0
1010    pr-url: https://github.com/nodejs/node/pull/6432
1011    description: Objects with circular references can be used as inputs now.
1012  - version:
1013    - v5.10.1
1014    - v4.4.3
1015    pr-url: https://github.com/nodejs/node/pull/5910
1016    description: Handle non-`Uint8Array` typed arrays correctly.
1017-->
1018
1019* `actual` {any}
1020* `expected` {any}
1021* `message` {string|Error}
1022
1023**Strict assertion mode**
1024
1025An alias of [`assert.notDeepStrictEqual()`][].
1026
1027**Legacy assertion mode**
1028
1029> Stability: 3 - Legacy: Use [`assert.notDeepStrictEqual()`][] instead.
1030
1031Tests for any deep inequality. Opposite of [`assert.deepEqual()`][].
1032
1033```js
1034const assert = require('assert');
1035
1036const obj1 = {
1037  a: {
1038    b: 1
1039  }
1040};
1041const obj2 = {
1042  a: {
1043    b: 2
1044  }
1045};
1046const obj3 = {
1047  a: {
1048    b: 1
1049  }
1050};
1051const obj4 = Object.create(obj1);
1052
1053assert.notDeepEqual(obj1, obj1);
1054// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
1055
1056assert.notDeepEqual(obj1, obj2);
1057// OK
1058
1059assert.notDeepEqual(obj1, obj3);
1060// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
1061
1062assert.notDeepEqual(obj1, obj4);
1063// OK
1064```
1065
1066If the values are deeply equal, an [`AssertionError`][] is thrown with a
1067`message` property set equal to the value of the `message` parameter. If the
1068`message` parameter is undefined, a default error message is assigned. If the
1069`message` parameter is an instance of an [`Error`][] then it will be thrown
1070instead of the `AssertionError`.
1071
1072## `assert.notDeepStrictEqual(actual, expected[, message])`
1073<!-- YAML
1074added: v1.2.0
1075changes:
1076  - version: v9.0.0
1077    pr-url: https://github.com/nodejs/node/pull/15398
1078    description: The `-0` and `+0` are not considered equal anymore.
1079  - version: v9.0.0
1080    pr-url: https://github.com/nodejs/node/pull/15036
1081    description: The `NaN` is now compared using the
1082              [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero)
1083              comparison.
1084  - version: v9.0.0
1085    pr-url: https://github.com/nodejs/node/pull/15001
1086    description: The `Error` names and messages are now properly compared.
1087  - version: v8.0.0
1088    pr-url: https://github.com/nodejs/node/pull/12142
1089    description: The `Set` and `Map` content is also compared.
1090  - version:
1091    - v6.4.0
1092    - v4.7.1
1093    pr-url: https://github.com/nodejs/node/pull/8002
1094    description: Typed array slices are handled correctly now.
1095  - version: v6.1.0
1096    pr-url: https://github.com/nodejs/node/pull/6432
1097    description: Objects with circular references can be used as inputs now.
1098  - version:
1099    - v5.10.1
1100    - v4.4.3
1101    pr-url: https://github.com/nodejs/node/pull/5910
1102    description: Handle non-`Uint8Array` typed arrays correctly.
1103-->
1104
1105* `actual` {any}
1106* `expected` {any}
1107* `message` {string|Error}
1108
1109Tests for deep strict inequality. Opposite of [`assert.deepStrictEqual()`][].
1110
1111```js
1112const assert = require('assert').strict;
1113
1114assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
1115// OK
1116```
1117
1118If the values are deeply and strictly equal, an [`AssertionError`][] is thrown
1119with a `message` property set equal to the value of the `message` parameter. If
1120the `message` parameter is undefined, a default error message is assigned. If
1121the `message` parameter is an instance of an [`Error`][] then it will be thrown
1122instead of the [`AssertionError`][].
1123
1124## `assert.notEqual(actual, expected[, message])`
1125<!-- YAML
1126added: v0.1.21
1127changes:
1128  - version: v14.18.0
1129    pr-url: https://github.com/nodejs/node/pull/38113
1130    description: In Legacy assertion mode, changed status from Deprecated to
1131                 Legacy.
1132  - version: v14.0.0
1133    pr-url: https://github.com/nodejs/node/pull/30766
1134    description: NaN is now treated as being identical in case both sides are
1135                 NaN.
1136-->
1137
1138* `actual` {any}
1139* `expected` {any}
1140* `message` {string|Error}
1141
1142**Strict assertion mode**
1143
1144An alias of [`assert.notStrictEqual()`][].
1145
1146**Legacy assertion mode**
1147
1148> Stability: 3 - Legacy: Use [`assert.notStrictEqual()`][] instead.
1149
1150Tests shallow, coercive inequality with the [Abstract Equality Comparison][]
1151(`!=` ). `NaN` is special handled and treated as being identical in case both
1152sides are `NaN`.
1153
1154```js
1155const assert = require('assert');
1156
1157assert.notEqual(1, 2);
1158// OK
1159
1160assert.notEqual(1, 1);
1161// AssertionError: 1 != 1
1162
1163assert.notEqual(1, '1');
1164// AssertionError: 1 != '1'
1165```
1166
1167If the values are equal, an [`AssertionError`][] is thrown with a `message`
1168property set equal to the value of the `message` parameter. If the `message`
1169parameter is undefined, a default error message is assigned. If the `message`
1170parameter is an instance of an [`Error`][] then it will be thrown instead of the
1171`AssertionError`.
1172
1173## `assert.notStrictEqual(actual, expected[, message])`
1174<!-- YAML
1175added: v0.1.21
1176changes:
1177  - version: v10.0.0
1178    pr-url: https://github.com/nodejs/node/pull/17003
1179    description: Used comparison changed from Strict Equality to `Object.is()`.
1180-->
1181
1182* `actual` {any}
1183* `expected` {any}
1184* `message` {string|Error}
1185
1186Tests strict inequality between the `actual` and `expected` parameters as
1187determined by the [SameValue Comparison][].
1188
1189```js
1190const assert = require('assert').strict;
1191
1192assert.notStrictEqual(1, 2);
1193// OK
1194
1195assert.notStrictEqual(1, 1);
1196// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
1197//
1198// 1
1199
1200assert.notStrictEqual(1, '1');
1201// OK
1202```
1203
1204If the values are strictly equal, an [`AssertionError`][] is thrown with a
1205`message` property set equal to the value of the `message` parameter. If the
1206`message` parameter is undefined, a default error message is assigned. If the
1207`message` parameter is an instance of an [`Error`][] then it will be thrown
1208instead of the `AssertionError`.
1209
1210## `assert.ok(value[, message])`
1211<!-- YAML
1212added: v0.1.21
1213changes:
1214  - version: v10.0.0
1215    pr-url: https://github.com/nodejs/node/pull/18319
1216    description: The `assert.ok()` (no arguments) will now use a predefined
1217                 error message.
1218-->
1219
1220* `value` {any}
1221* `message` {string|Error}
1222
1223Tests if `value` is truthy. It is equivalent to
1224`assert.equal(!!value, true, message)`.
1225
1226If `value` is not truthy, an [`AssertionError`][] is thrown with a `message`
1227property set equal to the value of the `message` parameter. If the `message`
1228parameter is `undefined`, a default error message is assigned. If the `message`
1229parameter is an instance of an [`Error`][] then it will be thrown instead of the
1230`AssertionError`.
1231If no arguments are passed in at all `message` will be set to the string:
1232``'No value argument passed to `assert.ok()`'``.
1233
1234Be aware that in the `repl` the error message will be different to the one
1235thrown in a file! See below for further details.
1236
1237```js
1238const assert = require('assert').strict;
1239
1240assert.ok(true);
1241// OK
1242assert.ok(1);
1243// OK
1244
1245assert.ok();
1246// AssertionError: No value argument passed to `assert.ok()`
1247
1248assert.ok(false, 'it\'s false');
1249// AssertionError: it's false
1250
1251// In the repl:
1252assert.ok(typeof 123 === 'string');
1253// AssertionError: false == true
1254
1255// In a file (e.g. test.js):
1256assert.ok(typeof 123 === 'string');
1257// AssertionError: The expression evaluated to a falsy value:
1258//
1259//   assert.ok(typeof 123 === 'string')
1260
1261assert.ok(false);
1262// AssertionError: The expression evaluated to a falsy value:
1263//
1264//   assert.ok(false)
1265
1266assert.ok(0);
1267// AssertionError: The expression evaluated to a falsy value:
1268//
1269//   assert.ok(0)
1270
1271// Using `assert()` works the same:
1272assert(0);
1273// AssertionError: The expression evaluated to a falsy value:
1274//
1275//   assert(0)
1276```
1277
1278## `assert.rejects(asyncFn[, error][, message])`
1279<!-- YAML
1280added: v10.0.0
1281-->
1282
1283* `asyncFn` {Function|Promise}
1284* `error` {RegExp|Function|Object|Error}
1285* `message` {string}
1286
1287Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
1288calls the function and awaits the returned promise to complete. It will then
1289check that the promise is rejected.
1290
1291If `asyncFn` is a function and it throws an error synchronously,
1292`assert.rejects()` will return a rejected `Promise` with that error. If the
1293function does not return a promise, `assert.rejects()` will return a rejected
1294`Promise` with an [`ERR_INVALID_RETURN_VALUE`][] error. In both cases the error
1295handler is skipped.
1296
1297Besides the async nature to await the completion behaves identically to
1298[`assert.throws()`][].
1299
1300If specified, `error` can be a [`Class`][], [`RegExp`][], a validation function,
1301an object where each property will be tested for, or an instance of error where
1302each property will be tested for including the non-enumerable `message` and
1303`name` properties.
1304
1305If specified, `message` will be the message provided by the [`AssertionError`][]
1306if the `asyncFn` fails to reject.
1307
1308```js
1309(async () => {
1310  await assert.rejects(
1311    async () => {
1312      throw new TypeError('Wrong value');
1313    },
1314    {
1315      name: 'TypeError',
1316      message: 'Wrong value'
1317    }
1318  );
1319})();
1320```
1321
1322```js
1323(async () => {
1324  await assert.rejects(
1325    async () => {
1326      throw new TypeError('Wrong value');
1327    },
1328    (err) => {
1329      assert.strictEqual(err.name, 'TypeError');
1330      assert.strictEqual(err.message, 'Wrong value');
1331      return true;
1332    }
1333  );
1334})();
1335```
1336
1337```js
1338assert.rejects(
1339  Promise.reject(new Error('Wrong value')),
1340  Error
1341).then(() => {
1342  // ...
1343});
1344```
1345
1346`error` cannot be a string. If a string is provided as the second
1347argument, then `error` is assumed to be omitted and the string will be used for
1348`message` instead. This can lead to easy-to-miss mistakes. Please read the
1349example in [`assert.throws()`][] carefully if using a string as the second
1350argument gets considered.
1351
1352## `assert.strictEqual(actual, expected[, message])`
1353<!-- YAML
1354added: v0.1.21
1355changes:
1356  - version: v10.0.0
1357    pr-url: https://github.com/nodejs/node/pull/17003
1358    description: Used comparison changed from Strict Equality to `Object.is()`.
1359-->
1360
1361* `actual` {any}
1362* `expected` {any}
1363* `message` {string|Error}
1364
1365Tests strict equality between the `actual` and `expected` parameters as
1366determined by the [SameValue Comparison][].
1367
1368```js
1369const assert = require('assert').strict;
1370
1371assert.strictEqual(1, 2);
1372// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
1373//
1374// 1 !== 2
1375
1376assert.strictEqual(1, 1);
1377// OK
1378
1379assert.strictEqual('Hello foobar', 'Hello World!');
1380// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
1381// + actual - expected
1382//
1383// + 'Hello foobar'
1384// - 'Hello World!'
1385//          ^
1386
1387const apples = 1;
1388const oranges = 2;
1389assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
1390// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
1391
1392assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
1393// TypeError: Inputs are not identical
1394```
1395
1396If the values are not strictly equal, an [`AssertionError`][] is thrown with a
1397`message` property set equal to the value of the `message` parameter. If the
1398`message` parameter is undefined, a default error message is assigned. If the
1399`message` parameter is an instance of an [`Error`][] then it will be thrown
1400instead of the [`AssertionError`][].
1401
1402## `assert.throws(fn[, error][, message])`
1403<!-- YAML
1404added: v0.1.21
1405changes:
1406  - version: v10.2.0
1407    pr-url: https://github.com/nodejs/node/pull/20485
1408    description: The `error` parameter can be an object containing regular
1409                 expressions now.
1410  - version: v9.9.0
1411    pr-url: https://github.com/nodejs/node/pull/17584
1412    description: The `error` parameter can now be an object as well.
1413  - version: v4.2.0
1414    pr-url: https://github.com/nodejs/node/pull/3276
1415    description: The `error` parameter can now be an arrow function.
1416-->
1417
1418* `fn` {Function}
1419* `error` {RegExp|Function|Object|Error}
1420* `message` {string}
1421
1422Expects the function `fn` to throw an error.
1423
1424If specified, `error` can be a [`Class`][], [`RegExp`][], a validation function,
1425a validation object where each property will be tested for strict deep equality,
1426or an instance of error where each property will be tested for strict deep
1427equality including the non-enumerable `message` and `name` properties. When
1428using an object, it is also possible to use a regular expression, when
1429validating against a string property. See below for examples.
1430
1431If specified, `message` will be appended to the message provided by the
1432`AssertionError` if the `fn` call fails to throw or in case the error validation
1433fails.
1434
1435Custom validation object/error instance:
1436
1437```js
1438const err = new TypeError('Wrong value');
1439err.code = 404;
1440err.foo = 'bar';
1441err.info = {
1442  nested: true,
1443  baz: 'text'
1444};
1445err.reg = /abc/i;
1446
1447assert.throws(
1448  () => {
1449    throw err;
1450  },
1451  {
1452    name: 'TypeError',
1453    message: 'Wrong value',
1454    info: {
1455      nested: true,
1456      baz: 'text'
1457    }
1458    // Only properties on the validation object will be tested for.
1459    // Using nested objects requires all properties to be present. Otherwise
1460    // the validation is going to fail.
1461  }
1462);
1463
1464// Using regular expressions to validate error properties:
1465assert.throws(
1466  () => {
1467    throw err;
1468  },
1469  {
1470    // The `name` and `message` properties are strings and using regular
1471    // expressions on those will match against the string. If they fail, an
1472    // error is thrown.
1473    name: /^TypeError$/,
1474    message: /Wrong/,
1475    foo: 'bar',
1476    info: {
1477      nested: true,
1478      // It is not possible to use regular expressions for nested properties!
1479      baz: 'text'
1480    },
1481    // The `reg` property contains a regular expression and only if the
1482    // validation object contains an identical regular expression, it is going
1483    // to pass.
1484    reg: /abc/i
1485  }
1486);
1487
1488// Fails due to the different `message` and `name` properties:
1489assert.throws(
1490  () => {
1491    const otherErr = new Error('Not found');
1492    // Copy all enumerable properties from `err` to `otherErr`.
1493    for (const [key, value] of Object.entries(err)) {
1494      otherErr[key] = value;
1495    }
1496    throw otherErr;
1497  },
1498  // The error's `message` and `name` properties will also be checked when using
1499  // an error as validation object.
1500  err
1501);
1502```
1503
1504Validate instanceof using constructor:
1505
1506```js
1507assert.throws(
1508  () => {
1509    throw new Error('Wrong value');
1510  },
1511  Error
1512);
1513```
1514
1515Validate error message using [`RegExp`][]:
1516
1517Using a regular expression runs `.toString` on the error object, and will
1518therefore also include the error name.
1519
1520```js
1521assert.throws(
1522  () => {
1523    throw new Error('Wrong value');
1524  },
1525  /^Error: Wrong value$/
1526);
1527```
1528
1529Custom error validation:
1530
1531The function must return `true` to indicate all internal validations passed.
1532It will otherwise fail with an [`AssertionError`][].
1533
1534```js
1535assert.throws(
1536  () => {
1537    throw new Error('Wrong value');
1538  },
1539  (err) => {
1540    assert(err instanceof Error);
1541    assert(/value/.test(err));
1542    // Avoid returning anything from validation functions besides `true`.
1543    // Otherwise, it's not clear what part of the validation failed. Instead,
1544    // throw an error about the specific validation that failed (as done in this
1545    // example) and add as much helpful debugging information to that error as
1546    // possible.
1547    return true;
1548  },
1549  'unexpected error'
1550);
1551```
1552
1553`error` cannot be a string. If a string is provided as the second
1554argument, then `error` is assumed to be omitted and the string will be used for
1555`message` instead. This can lead to easy-to-miss mistakes. Using the same
1556message as the thrown error message is going to result in an
1557`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using
1558a string as the second argument gets considered:
1559
1560<!-- eslint-disable no-restricted-syntax -->
1561```js
1562function throwingFirst() {
1563  throw new Error('First');
1564}
1565
1566function throwingSecond() {
1567  throw new Error('Second');
1568}
1569
1570function notThrowing() {}
1571
1572// The second argument is a string and the input function threw an Error.
1573// The first case will not throw as it does not match for the error message
1574// thrown by the input function!
1575assert.throws(throwingFirst, 'Second');
1576// In the next example the message has no benefit over the message from the
1577// error and since it is not clear if the user intended to actually match
1578// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
1579assert.throws(throwingSecond, 'Second');
1580// TypeError [ERR_AMBIGUOUS_ARGUMENT]
1581
1582// The string is only used (as message) in case the function does not throw:
1583assert.throws(notThrowing, 'Second');
1584// AssertionError [ERR_ASSERTION]: Missing expected exception: Second
1585
1586// If it was intended to match for the error message do this instead:
1587// It does not throw because the error messages match.
1588assert.throws(throwingSecond, /Second$/);
1589
1590// If the error message does not match, an AssertionError is thrown.
1591assert.throws(throwingFirst, /Second$/);
1592// AssertionError [ERR_ASSERTION]
1593```
1594
1595Due to the confusing error-prone notation, avoid a string as the second
1596argument.
1597
1598[Abstract Equality Comparison]: https://tc39.github.io/ecma262/#sec-abstract-equality-comparison
1599[Object wrappers]: https://developer.mozilla.org/en-US/docs/Glossary/Primitive#Primitive_wrapper_objects_in_JavaScript
1600[Object.prototype.toString()]: https://tc39.github.io/ecma262/#sec-object.prototype.tostring
1601[SameValue Comparison]: https://tc39.github.io/ecma262/#sec-samevalue
1602[Strict Equality Comparison]: https://tc39.github.io/ecma262/#sec-strict-equality-comparison
1603[`AssertionError`]: #assert_class_assert_assertionerror
1604[`CallTracker`]: #assert_class_assert_calltracker
1605[`Class`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
1606[`ERR_INVALID_RETURN_VALUE`]: errors.md#errors_err_invalid_return_value
1607[`Error.captureStackTrace`]: errors.md#errors_error_capturestacktrace_targetobject_constructoropt
1608[`Error`]: errors.md#errors_class_error
1609[`Map`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
1610[`Object.is()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
1611[`RegExp`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
1612[`Set`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
1613[`Symbol`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol
1614[`TypeError`]: errors.md#errors_class_typeerror
1615[`WeakMap`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap
1616[`WeakSet`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet
1617[`assert.deepEqual()`]: #assert_assert_deepequal_actual_expected_message
1618[`assert.deepStrictEqual()`]: #assert_assert_deepstrictequal_actual_expected_message
1619[`assert.doesNotThrow()`]: #assert_assert_doesnotthrow_fn_error_message
1620[`assert.equal()`]: #assert_assert_equal_actual_expected_message
1621[`assert.notDeepEqual()`]: #assert_assert_notdeepequal_actual_expected_message
1622[`assert.notDeepStrictEqual()`]: #assert_assert_notdeepstrictequal_actual_expected_message
1623[`assert.notEqual()`]: #assert_assert_notequal_actual_expected_message
1624[`assert.notStrictEqual()`]: #assert_assert_notstrictequal_actual_expected_message
1625[`assert.ok()`]: #assert_assert_ok_value_message
1626[`assert.strictEqual()`]: #assert_assert_strictequal_actual_expected_message
1627[`assert.throws()`]: #assert_assert_throws_fn_error_message
1628[`process.on('exit')`]: process.md#process_event_exit
1629[`tracker.calls()`]: #assert_tracker_calls_fn_exact
1630[`tracker.verify()`]: #assert_tracker_verify
1631[enumerable "own" properties]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties
1632[prototype-spec]: https://tc39.github.io/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots
1633[strict assertion mode]: #assert_strict_assertion_mode
1634