アサーション#

安定性: 2 - 安定

ソースコード: lib/assert.js

node:assert モジュールは、不変式を検証するためのアサーション関数のセットを提供します。

厳格なアサーションモード#

厳格なアサーションモードでは、非厳格なメソッドは対応する厳格なメソッドのように動作します。たとえば、assert.deepEqual()assert.deepStrictEqual() のように動作します。

厳格なアサーションモードでは、オブジェクトのエラーメッセージに差分が表示されます。レガシーアサーションモードでは、オブジェクトのエラーメッセージにはオブジェクトが表示され、多くの場合切り詰められます。

厳格なアサーションモードを使用するには

import { strict as assert } from 'node:assert';const assert = require('node:assert').strict;
import assert from 'node:assert/strict';const assert = require('node:assert/strict');

エラー差分の例

import { strict as assert } from 'node:assert';

assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected ... Lines skipped
//
//   [
//     [
// ...
//       2,
// +     3
// -     '3'
//     ],
// ...
//     5
//   ]const assert = require('node:assert/strict');

assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected ... Lines skipped
//
//   [
//     [
// ...
//       2,
// +     3
// -     '3'
//     ],
// ...
//     5
//   ]

色の表示を無効にするには、NO_COLOR または NODE_DISABLE_COLORS 環境変数を使用します。これにより、REPLでの色の表示も無効になります。ターミナル環境での色のサポートの詳細については、tty の getColorDepth() ドキュメントを参照してください。

レガシーアサーションモード#

レガシーアサーションモードは、== 演算子 を使用します。

レガシーアサーションモードを使用するには

import assert from 'node:assert';const assert = require('node:assert');

レガシーアサーションモードは、特に assert.deepEqual() を使用する場合、予期しない結果になる可能性があります。

// WARNING: This does not throw an AssertionError in legacy assertion mode!
assert.deepEqual(/a/gi, new Date()); 

クラス: assert.AssertionError[src]#

アサーションの失敗を示します。node:assert モジュールによってスローされるすべてのエラーは、AssertionError クラスのインスタンスになります。

new assert.AssertionError(options)#

  • options <オブジェクト>
    • message <文字列> 指定した場合、エラーメッセージはこの値に設定されます。
    • actual <任意> エラーインスタンスのactualプロパティ。
    • expected <任意> エラーインスタンスのexpectedプロパティ。
    • operator <文字列> エラーインスタンスのoperatorプロパティ。
    • stackStartFn <関数> 指定した場合、生成されたスタックトレースはこの関数より前のフレームを省略します。

アサーションの失敗を示すErrorのサブクラス。

すべてのインスタンスには、組み込みのErrorプロパティ(messagename)と

  • actual <任意> assert.strictEqual()などのメソッドのactual引数に設定されます。
  • expected <任意> assert.strictEqual()などのメソッドのexpected値に設定されます。
  • generatedMessage <ブール値> メッセージが自動生成されたかどうかを示します(trueの場合)。
  • code <文字列> 値は常にERR_ASSERTIONで、エラーがアサーションエラーであることを示します。
  • operator <文字列> 渡された演算子の値に設定されます。
import assert from 'node:assert';

// Generate an AssertionError to compare the error message later:
const { message } = new assert.AssertionError({
  actual: 1,
  expected: 2,
  operator: 'strictEqual',
});

// Verify error output:
try {
  assert.strictEqual(1, 2);
} catch (err) {
  assert(err instanceof assert.AssertionError);
  assert.strictEqual(err.message, message);
  assert.strictEqual(err.name, 'AssertionError');
  assert.strictEqual(err.actual, 1);
  assert.strictEqual(err.expected, 2);
  assert.strictEqual(err.code, 'ERR_ASSERTION');
  assert.strictEqual(err.operator, 'strictEqual');
  assert.strictEqual(err.generatedMessage, true);
}const assert = require('node:assert');

// Generate an AssertionError to compare the error message later:
const { message } = new assert.AssertionError({
  actual: 1,
  expected: 2,
  operator: 'strictEqual',
});

// Verify error output:
try {
  assert.strictEqual(1, 2);
} catch (err) {
  assert(err instanceof assert.AssertionError);
  assert.strictEqual(err.message, message);
  assert.strictEqual(err.name, 'AssertionError');
  assert.strictEqual(err.actual, 1);
  assert.strictEqual(err.expected, 2);
  assert.strictEqual(err.code, 'ERR_ASSERTION');
  assert.strictEqual(err.operator, 'strictEqual');
  assert.strictEqual(err.generatedMessage, true);
}

クラス: assert.CallTracker#

安定性: 0 - 非推奨

この機能は非推奨であり、将来のバージョンで削除されます。mock ヘルパー関数などの代替手段の使用を検討してください。

new assert.CallTracker()#

関数が特定の回数呼び出されたかどうかを追跡するために使用できる新しいCallTrackerオブジェクトを作成します。検証を行うには、tracker.verify()を呼び出す必要があります。通常の方法は、process.on('exit')ハンドラーで呼び出すことです。

import assert from 'node:assert';
import process from 'node:process';

const tracker = new assert.CallTracker();

function func() {}

// callsfunc() must be called exactly 1 time before tracker.verify().
const callsfunc = tracker.calls(func, 1);

callsfunc();

// Calls tracker.verify() and verifies if all tracker.calls() functions have
// been called exact times.
process.on('exit', () => {
  tracker.verify();
});const assert = require('node:assert');

const tracker = new assert.CallTracker();

function func() {}

// callsfunc() must be called exactly 1 time before tracker.verify().
const callsfunc = tracker.calls(func, 1);

callsfunc();

// Calls tracker.verify() and verifies if all tracker.calls() functions have
// been called exact times.
process.on('exit', () => {
  tracker.verify();
});

tracker.calls([fn][, exact])#

  • fn <関数> デフォルト: 何もしない関数。
  • exact <数値> デフォルト: 1
  • 戻り値: <関数> fnをラップする関数。

tracker.verify()が呼び出された時点で、ラッパー関数は正確にexact回呼び出されることが期待されます。 tracker.verify()が呼び出されたときに関数が正確にexact回呼び出されていない場合、tracker.verify()はエラーをスローします。

import assert from 'node:assert';

// Creates call tracker.
const tracker = new assert.CallTracker();

function func() {}

// Returns a function that wraps func() that must be called exact times
// before tracker.verify().
const callsfunc = tracker.calls(func);const assert = require('node:assert');

// Creates call tracker.
const tracker = new assert.CallTracker();

function func() {}

// Returns a function that wraps func() that must be called exact times
// before tracker.verify().
const callsfunc = tracker.calls(func);

tracker.getCalls(fn)#

import assert from 'node:assert';

const tracker = new assert.CallTracker();

function func() {}
const callsfunc = tracker.calls(func);
callsfunc(1, 2, 3);

assert.deepStrictEqual(tracker.getCalls(callsfunc),
                       [{ thisArg: undefined, arguments: [1, 2, 3] }]);const assert = require('node:assert');

// Creates call tracker.
const tracker = new assert.CallTracker();

function func() {}
const callsfunc = tracker.calls(func);
callsfunc(1, 2, 3);

assert.deepStrictEqual(tracker.getCalls(callsfunc),
                       [{ thisArg: undefined, arguments: [1, 2, 3] }]);

tracker.report()#

  • 戻り値: <Array> tracker.calls()によって返されるラッパー関数の情報を含むオブジェクトの配列。
  • オブジェクト <オブジェクト>
    • message <string>
    • actual <number> 関数が実際に呼び出された回数。
    • expected <number> 関数が呼び出されることが期待された回数。
    • operator <string> ラップされている関数の名前。
    • stack <Object> 関数のスタックトレース。

この配列には、期待された回数だけ呼び出されなかった関数の、期待された呼び出し回数と実際の呼び出し回数に関する情報が含まれています。

import assert from 'node:assert';

// Creates call tracker.
const tracker = new assert.CallTracker();

function func() {}

// Returns a function that wraps func() that must be called exact times
// before tracker.verify().
const callsfunc = tracker.calls(func, 2);

// Returns an array containing information on callsfunc()
console.log(tracker.report());
// [
//  {
//    message: 'Expected the func function to be executed 2 time(s) but was
//    executed 0 time(s).',
//    actual: 0,
//    expected: 2,
//    operator: 'func',
//    stack: stack trace
//  }
// ]const assert = require('node:assert');

// Creates call tracker.
const tracker = new assert.CallTracker();

function func() {}

// Returns a function that wraps func() that must be called exact times
// before tracker.verify().
const callsfunc = tracker.calls(func, 2);

// Returns an array containing information on callsfunc()
console.log(tracker.report());
// [
//  {
//    message: 'Expected the func function to be executed 2 time(s) but was
//    executed 0 time(s).',
//    actual: 0,
//    expected: 2,
//    operator: 'func',
//    stack: stack trace
//  }
// ]

tracker.reset([fn])#

  • fn <Function> リセットするトラッキングされた関数。

コールトラッカーの呼び出しをリセットします。トラッキングされた関数を引数として渡すと、その関数の呼び出しがリセットされます。引数を渡さないと、すべてのトラッキングされた関数がリセットされます。

import assert from 'node:assert';

const tracker = new assert.CallTracker();

function func() {}
const callsfunc = tracker.calls(func);

callsfunc();
// Tracker was called once
assert.strictEqual(tracker.getCalls(callsfunc).length, 1);

tracker.reset(callsfunc);
assert.strictEqual(tracker.getCalls(callsfunc).length, 0);const assert = require('node:assert');

const tracker = new assert.CallTracker();

function func() {}
const callsfunc = tracker.calls(func);

callsfunc();
// Tracker was called once
assert.strictEqual(tracker.getCalls(callsfunc).length, 1);

tracker.reset(callsfunc);
assert.strictEqual(tracker.getCalls(callsfunc).length, 0);

tracker.verify()#

tracker.calls()に渡された関数のリストを反復処理し、期待された回数だけ呼び出されていない関数に対してエラーをスローします。

import assert from 'node:assert';

// Creates call tracker.
const tracker = new assert.CallTracker();

function func() {}

// Returns a function that wraps func() that must be called exact times
// before tracker.verify().
const callsfunc = tracker.calls(func, 2);

callsfunc();

// Will throw an error since callsfunc() was only called once.
tracker.verify();const assert = require('node:assert');

// Creates call tracker.
const tracker = new assert.CallTracker();

function func() {}

// Returns a function that wraps func() that must be called exact times
// before tracker.verify().
const callsfunc = tracker.calls(func, 2);

callsfunc();

// Will throw an error since callsfunc() was only called once.
tracker.verify();

assert(value[, message])#

assert.ok()のエイリアス。

assert.deepEqual(actual, expected[, message])#

厳格なアサーションモード

assert.deepStrictEqual()のエイリアス。

レガシーアサーションモード

安定性: 3 - レガシー: 代わりにassert.deepStrictEqual()を使用してください。

actualパラメータとexpectedパラメータ間の深い等価性をテストします。assert.deepStrictEqual()の使用を検討してください。assert.deepEqual()は予期せぬ結果になる可能性があります。

深い等価性とは、子オブジェクトの列挙可能な「独自の」プロパティも、以下のルールに従って再帰的に評価されることを意味します。

比較の詳細#

  • プリミティブ値は、NaNを除いて==演算子を使用して比較されます。両方がNaNの場合、同一として扱われます。
  • オブジェクトの型タグは同じである必要があります。
  • 列挙可能な「独自の」プロパティのみが考慮されます。
  • Errorの名前とメッセージは、列挙可能なプロパティでなくても常に比較されます。
  • オブジェクトラッパーは、オブジェクトとラップされていない値の両方として比較されます。
  • Objectのプロパティは、順序なしで比較されます。
  • MapのキーとSetの項目は、順序なしで比較されます。
  • 両方が異なるとき、または両方が循環参照に遭遇したときに、再帰は停止します。
  • 実装では、オブジェクトの[[Prototype]]はテストしません。
  • Symbolのプロパティは比較されません。
  • WeakMapWeakSetの比較は、それらの値に依存しません。
  • RegExpのlastIndex、フラグ、ソースは、列挙可能なプロパティでなくても常に比較されます。

次の例では、プリミティブが==演算子を使用して比較されるため、AssertionErrorはスローされません。

import assert from 'node:assert';
// WARNING: This does not throw an AssertionError!

assert.deepEqual('+00000000', false);const assert = require('node:assert');
// WARNING: This does not throw an AssertionError!

assert.deepEqual('+00000000', false);

「深い」等価性とは、子オブジェクトの列挙可能な「独自の」プロパティも評価されることを意味します。

import assert from 'node:assert';

const obj1 = {
  a: {
    b: 1,
  },
};
const obj2 = {
  a: {
    b: 2,
  },
};
const obj3 = {
  a: {
    b: 1,
  },
};
const obj4 = { __proto__: obj1 };

assert.deepEqual(obj1, obj1);
// OK

// Values of b are different:
assert.deepEqual(obj1, obj2);
// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }

assert.deepEqual(obj1, obj3);
// OK

// Prototypes are ignored:
assert.deepEqual(obj1, obj4);
// AssertionError: { a: { b: 1 } } deepEqual {}const assert = require('node:assert');

const obj1 = {
  a: {
    b: 1,
  },
};
const obj2 = {
  a: {
    b: 2,
  },
};
const obj3 = {
  a: {
    b: 1,
  },
};
const obj4 = { __proto__: obj1 };

assert.deepEqual(obj1, obj1);
// OK

// Values of b are different:
assert.deepEqual(obj1, obj2);
// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }

assert.deepEqual(obj1, obj3);
// OK

// Prototypes are ignored:
assert.deepEqual(obj1, obj4);
// AssertionError: { a: { b: 1 } } deepEqual {}

値が等しくない場合、messageプロパティがmessageパラメータの値に設定されたAssertionErrorがスローされます。messageパラメータが未定義の場合、デフォルトのエラーメッセージが割り当てられます。messageパラメータがErrorのインスタンスである場合、AssertionErrorの代わりにそれがスローされます。

assert.deepStrictEqual(actual, expected[, message])#

actualパラメータとexpectedパラメータ間の深い等価性をテストします。「深い」等価性とは、子オブジェクトの列挙可能な「独自の」プロパティも、以下のルールに従って再帰的に評価されることを意味します。

比較の詳細#

  • プリミティブ値はObject.is()を使用して比較されます。
  • オブジェクトの型タグは同じである必要があります。
  • オブジェクトの[[Prototype]]===演算子を使用して比較されます。
  • 列挙可能な「独自の」プロパティのみが考慮されます。
  • Errorの名前とメッセージは、列挙可能なプロパティでなくても常に比較されます。
  • 列挙可能な独自のSymbolプロパティも比較されます。
  • オブジェクトラッパーは、オブジェクトとラップされていない値の両方として比較されます。
  • Objectのプロパティは、順序なしで比較されます。
  • MapのキーとSetの項目は、順序なしで比較されます。
  • 両方が異なるとき、または両方が循環参照に遭遇したときに、再帰は停止します。
  • WeakMapWeakSetの比較は、それらの値に依存しません。詳細は下記を参照してください。
  • RegExpのlastIndex、フラグ、ソースは、列挙可能なプロパティでなくても常に比較されます。
import assert from 'node:assert/strict';

// This fails because 1 !== '1'.
assert.deepStrictEqual({ a: 1 }, { a: '1' });
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
//   {
// +   a: 1
// -   a: '1'
//   }

// The following objects don't have own properties
const date = new Date();
const object = {};
const fakeDate = {};
Object.setPrototypeOf(fakeDate, Date.prototype);

// Different [[Prototype]]:
assert.deepStrictEqual(object, fakeDate);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + {}
// - Date {}

// Different type tags:
assert.deepStrictEqual(date, fakeDate);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + 2018-04-26T00:49:08.604Z
// - Date {}

assert.deepStrictEqual(NaN, NaN);
// OK because Object.is(NaN, NaN) is true.

// Different unwrapped numbers:
assert.deepStrictEqual(new Number(1), new Number(2));
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + [Number: 1]
// - [Number: 2]

assert.deepStrictEqual(new String('foo'), Object('foo'));
// OK because the object and the string are identical when unwrapped.

assert.deepStrictEqual(-0, -0);
// OK

// Different zeros:
assert.deepStrictEqual(0, -0);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + 0
// - -0

const symbol1 = Symbol();
const symbol2 = Symbol();
assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
// OK, because it is the same symbol on both objects.

assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:
//
// {
//   [Symbol()]: 1
// }

const weakMap1 = new WeakMap();
const weakMap2 = new WeakMap([[{}, {}]]);
const weakMap3 = new WeakMap();
weakMap3.unequal = true;

assert.deepStrictEqual(weakMap1, weakMap2);
// OK, because it is impossible to compare the entries

// Fails because weakMap3 has a property that weakMap1 does not contain:
assert.deepStrictEqual(weakMap1, weakMap3);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
//   WeakMap {
// +   [items unknown]
// -   [items unknown],
// -   unequal: true
//   }const assert = require('node:assert/strict');

// This fails because 1 !== '1'.
assert.deepStrictEqual({ a: 1 }, { a: '1' });
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
//   {
// +   a: 1
// -   a: '1'
//   }

// The following objects don't have own properties
const date = new Date();
const object = {};
const fakeDate = {};
Object.setPrototypeOf(fakeDate, Date.prototype);

// Different [[Prototype]]:
assert.deepStrictEqual(object, fakeDate);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + {}
// - Date {}

// Different type tags:
assert.deepStrictEqual(date, fakeDate);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + 2018-04-26T00:49:08.604Z
// - Date {}

assert.deepStrictEqual(NaN, NaN);
// OK because Object.is(NaN, NaN) is true.

// Different unwrapped numbers:
assert.deepStrictEqual(new Number(1), new Number(2));
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + [Number: 1]
// - [Number: 2]

assert.deepStrictEqual(new String('foo'), Object('foo'));
// OK because the object and the string are identical when unwrapped.

assert.deepStrictEqual(-0, -0);
// OK

// Different zeros:
assert.deepStrictEqual(0, -0);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + 0
// - -0

const symbol1 = Symbol();
const symbol2 = Symbol();
assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
// OK, because it is the same symbol on both objects.

assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:
//
// {
//   [Symbol()]: 1
// }

const weakMap1 = new WeakMap();
const weakMap2 = new WeakMap([[{}, {}]]);
const weakMap3 = new WeakMap();
weakMap3.unequal = true;

assert.deepStrictEqual(weakMap1, weakMap2);
// OK, because it is impossible to compare the entries

// Fails because weakMap3 has a property that weakMap1 does not contain:
assert.deepStrictEqual(weakMap1, weakMap3);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
//   WeakMap {
// +   [items unknown]
// -   [items unknown],
// -   unequal: true
//   }

値が等しくない場合、messageプロパティがmessageパラメータの値に設定されたAssertionErrorがスローされます。messageパラメータが未定義の場合、デフォルトのエラーメッセージが割り当てられます。messageパラメータがErrorのインスタンスである場合、AssertionErrorの代わりにそれがスローされます。

assert.doesNotMatch(string, regexp[, message])#

string入力が正規表現と一致しないことを期待します。

import assert from 'node:assert/strict';

assert.doesNotMatch('I will fail', /fail/);
// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...

assert.doesNotMatch(123, /pass/);
// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.

assert.doesNotMatch('I will pass', /different/);
// OKconst assert = require('node:assert/strict');

assert.doesNotMatch('I will fail', /fail/);
// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...

assert.doesNotMatch(123, /pass/);
// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.

assert.doesNotMatch('I will pass', /different/);
// OK

値が一致する場合、またはstring引数がstring以外の型である場合、messageプロパティがmessageパラメータの値に設定されたAssertionErrorがスローされます。messageパラメータが未定義の場合、デフォルトのエラーメッセージが割り当てられます。messageパラメータがErrorのインスタンスである場合、AssertionErrorの代わりにそれがスローされます。

assert.doesNotReject(asyncFn[, error][, message])#

asyncFnプロミスを待機するか、asyncFnが関数の場合、関数をすぐに呼び出して返されたプロミスが完了するのを待機します。その後、プロミスが拒否されていないことを確認します。

asyncFn が関数であり、同期的にエラーをスローした場合、assert.doesNotReject() はそのエラーを含む rejected Promise を返します。関数がプロミスを返さない場合、assert.doesNotReject()ERR_INVALID_RETURN_VALUE エラーを含む rejected Promise を返します。どちらの場合も、エラーハンドラーはスキップされます。

実際、assert.doesNotReject() は役に立ちません。拒否をキャッチして再度拒否することにはほとんどメリットがないためです。代わりに、拒否されないはずの特定のコードパスにコメントを追加し、エラーメッセージをできるだけ分かりやすくすることを検討してください。

指定されている場合、errorClassRegExp、または検証関数にすることができます。assert.throws() を参照して詳細を確認してください。

非同期であることを除けば、完了を待つ動作は assert.doesNotThrow() と同じです。

import assert from 'node:assert/strict';

await assert.doesNotReject(
  async () => {
    throw new TypeError('Wrong value');
  },
  SyntaxError,
);const assert = require('node:assert/strict');

(async () => {
  await assert.doesNotReject(
    async () => {
      throw new TypeError('Wrong value');
    },
    SyntaxError,
  );
})();
import assert from 'node:assert/strict';

assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
  .then(() => {
    // ...
  });const assert = require('node:assert/strict');

assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
  .then(() => {
    // ...
  });

assert.doesNotThrow(fn[, error][, message])#

関数 fn がエラーをスローしないことをアサートします。

実際、assert.doesNotThrow() は役に立ちません。エラーをキャッチして再度スローすることにはメリットがないためです。代わりに、エラーをスローしないはずの特定のコードパスにコメントを追加し、エラーメッセージをできるだけ分かりやすくすることを検討してください。

assert.doesNotThrow() が呼び出されると、すぐに fn 関数が呼び出されます。

エラーがスローされ、それが error パラメータで指定された型と同じ場合、AssertionError がスローされます。エラーの型が異なる場合、または error パラメータが未定義の場合、エラーは呼び出し元に伝播されます。

指定されている場合、errorClassRegExp、または検証関数にすることができます。assert.throws() を参照して詳細を確認してください。

たとえば、次の例では、アサーションに一致するエラー型がないため、TypeError がスローされます。

import assert from 'node:assert/strict';

assert.doesNotThrow(
  () => {
    throw new TypeError('Wrong value');
  },
  SyntaxError,
);const assert = require('node:assert/strict');

assert.doesNotThrow(
  () => {
    throw new TypeError('Wrong value');
  },
  SyntaxError,
);

しかし、次の例では、メッセージ 'Got unwanted exception...' を含む AssertionError が発生します。

import assert from 'node:assert/strict';

assert.doesNotThrow(
  () => {
    throw new TypeError('Wrong value');
  },
  TypeError,
);const assert = require('node:assert/strict');

assert.doesNotThrow(
  () => {
    throw new TypeError('Wrong value');
  },
  TypeError,
);

AssertionError がスローされ、message パラメータに値が指定されている場合、message の値は AssertionError のメッセージに追加されます。

import assert from 'node:assert/strict';

assert.doesNotThrow(
  () => {
    throw new TypeError('Wrong value');
  },
  /Wrong value/,
  'Whoops',
);
// Throws: AssertionError: Got unwanted exception: Whoopsconst assert = require('node:assert/strict');

assert.doesNotThrow(
  () => {
    throw new TypeError('Wrong value');
  },
  /Wrong value/,
  'Whoops',
);
// Throws: AssertionError: Got unwanted exception: Whoops

assert.equal(actual, expected[, message])#

厳格なアサーションモード

assert.strictEqual() のエイリアスです。

レガシーアサーションモード

安定性: 3 - 従来: 代わりに assert.strictEqual() を使用してください。

== 演算子 を使用して、actual パラメータと expected パラメータ間の浅い、強制的な等価性をテストします。NaN は特別に処理され、両側が NaN の場合は同一と見なされます。

import assert from 'node:assert';

assert.equal(1, 1);
// OK, 1 == 1
assert.equal(1, '1');
// OK, 1 == '1'
assert.equal(NaN, NaN);
// OK

assert.equal(1, 2);
// AssertionError: 1 == 2
assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }const assert = require('node:assert');

assert.equal(1, 1);
// OK, 1 == 1
assert.equal(1, '1');
// OK, 1 == '1'
assert.equal(NaN, NaN);
// OK

assert.equal(1, 2);
// AssertionError: 1 == 2
assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }

値が等しくない場合、messageプロパティがmessageパラメータの値に設定されたAssertionErrorがスローされます。messageパラメータが未定義の場合、デフォルトのエラーメッセージが割り当てられます。messageパラメータがErrorのインスタンスである場合、AssertionErrorの代わりにそれがスローされます。

assert.fail([message])#

指定されたエラーメッセージ、またはデフォルトのエラーメッセージで AssertionError をスローします。message パラメータが Error のインスタンスである場合、AssertionError の代わりにそれがスローされます。

import assert from 'node:assert/strict';

assert.fail();
// AssertionError [ERR_ASSERTION]: Failed

assert.fail('boom');
// AssertionError [ERR_ASSERTION]: boom

assert.fail(new TypeError('need array'));
// TypeError: need arrayconst assert = require('node:assert/strict');

assert.fail();
// AssertionError [ERR_ASSERTION]: Failed

assert.fail('boom');
// AssertionError [ERR_ASSERTION]: boom

assert.fail(new TypeError('need array'));
// TypeError: need array

2つ以上の引数を使用して assert.fail() を使用する事は可能ですが、非推奨です。詳細は下記を参照してください。

assert.fail(actual, expected[, message[, operator[, stackStartFn]]])#

安定性: 0 - 非推奨: 代わりに assert.fail([message]) または他のアサート関数を使用してください。

message が偽の場合、エラーメッセージは、指定された operator で区切られた actualexpected の値として設定されます。actualexpected の2つの引数のみが提供されている場合、operator はデフォルトで '!=' になります。message が3番目の引数として提供されている場合、それはエラーメッセージとして使用され、他の引数はスローされたオブジェクトのプロパティとして格納されます。stackStartFn が提供されている場合、その関数よりも上のすべてのスタックフレームはスタックトレースから削除されます(Error.captureStackTrace を参照)。引数が指定されていない場合、デフォルトのメッセージ Failed が使用されます。

import assert from 'node:assert/strict';

assert.fail('a', 'b');
// AssertionError [ERR_ASSERTION]: 'a' != 'b'

assert.fail(1, 2, undefined, '>');
// AssertionError [ERR_ASSERTION]: 1 > 2

assert.fail(1, 2, 'fail');
// AssertionError [ERR_ASSERTION]: fail

assert.fail(1, 2, 'whoops', '>');
// AssertionError [ERR_ASSERTION]: whoops

assert.fail(1, 2, new TypeError('need array'));
// TypeError: need arrayconst assert = require('node:assert/strict');

assert.fail('a', 'b');
// AssertionError [ERR_ASSERTION]: 'a' != 'b'

assert.fail(1, 2, undefined, '>');
// AssertionError [ERR_ASSERTION]: 1 > 2

assert.fail(1, 2, 'fail');
// AssertionError [ERR_ASSERTION]: fail

assert.fail(1, 2, 'whoops', '>');
// AssertionError [ERR_ASSERTION]: whoops

assert.fail(1, 2, new TypeError('need array'));
// TypeError: need array

最後3つのケースでは、actualexpected、および operator はエラーメッセージに影響しません。

例外のスタックトレースを切り詰めるための stackStartFn の使用例

import assert from 'node:assert/strict';

function suppressFrame() {
  assert.fail('a', 'b', undefined, '!==', suppressFrame);
}
suppressFrame();
// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
//     at repl:1:1
//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)
//     ...const assert = require('node:assert/strict');

function suppressFrame() {
  assert.fail('a', 'b', undefined, '!==', suppressFrame);
}
suppressFrame();
// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
//     at repl:1:1
//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)
//     ...

assert.ifError(value)#

valueundefined でも null でもない場合、value をスローします。これは、コールバックの error 引数をテストする場合に役立ちます。スタックトレースには、ifError() に渡されたエラーからのすべてのフレームが含まれ、ifError() 自体の潜在的な新しいフレームも含まれます。

import assert from 'node:assert/strict';

assert.ifError(null);
// OK
assert.ifError(0);
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
assert.ifError('error');
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
assert.ifError(new Error());
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error

// Create some random error frames.
let err;
(function errorFrame() {
  err = new Error('test error');
})();

(function ifErrorFrame() {
  assert.ifError(err);
})();
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
//     at ifErrorFrame
//     at errorFrameconst assert = require('node:assert/strict');

assert.ifError(null);
// OK
assert.ifError(0);
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
assert.ifError('error');
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
assert.ifError(new Error());
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error

// Create some random error frames.
let err;
(function errorFrame() {
  err = new Error('test error');
})();

(function ifErrorFrame() {
  assert.ifError(err);
})();
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
//     at ifErrorFrame
//     at errorFrame

assert.match(string, regexp[, message])#

string 入力値が正規表現に一致することを期待します。

import assert from 'node:assert/strict';

assert.match('I will fail', /pass/);
// AssertionError [ERR_ASSERTION]: The input did not match the regular ...

assert.match(123, /pass/);
// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.

assert.match('I will pass', /pass/);
// OKconst assert = require('node:assert/strict');

assert.match('I will fail', /pass/);
// AssertionError [ERR_ASSERTION]: The input did not match the regular ...

assert.match(123, /pass/);
// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.

assert.match('I will pass', /pass/);
// OK

値が一致しない場合、または string 引数が string 以外の型である場合、message プロパティが message パラメータの値に設定された AssertionError がスローされます。message パラメータが未定義の場合、デフォルトのエラーメッセージが割り当てられます。message パラメータが Error のインスタンスである場合、AssertionError の代わりにそれがスローされます。

assert.notDeepEqual(actual, expected[, message])#

厳格なアサーションモード

assert.notDeepStrictEqual() のエイリアスです。

レガシーアサーションモード

安定性: 3 - 従来: 代わりに assert.notDeepStrictEqual() を使用してください。

assert.deepEqual() の逆で、深い不等価性をテストします。

import assert from 'node:assert';

const obj1 = {
  a: {
    b: 1,
  },
};
const obj2 = {
  a: {
    b: 2,
  },
};
const obj3 = {
  a: {
    b: 1,
  },
};
const obj4 = { __proto__: obj1 };

assert.notDeepEqual(obj1, obj1);
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }

assert.notDeepEqual(obj1, obj2);
// OK

assert.notDeepEqual(obj1, obj3);
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }

assert.notDeepEqual(obj1, obj4);
// OKconst assert = require('node:assert');

const obj1 = {
  a: {
    b: 1,
  },
};
const obj2 = {
  a: {
    b: 2,
  },
};
const obj3 = {
  a: {
    b: 1,
  },
};
const obj4 = { __proto__: obj1 };

assert.notDeepEqual(obj1, obj1);
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }

assert.notDeepEqual(obj1, obj2);
// OK

assert.notDeepEqual(obj1, obj3);
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }

assert.notDeepEqual(obj1, obj4);
// OK

値が深く等しい場合、message プロパティが message パラメータの値に設定された AssertionError がスローされます。message パラメータが未定義の場合、デフォルトのエラーメッセージが割り当てられます。message パラメータが Error のインスタンスである場合、AssertionError の代わりにそれがスローされます。

assert.notDeepStrictEqual(actual, expected[, message])#

assert.deepStrictEqual() の逆で、深い厳密な不等価性をテストします。

import assert from 'node:assert/strict';

assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
// OKconst assert = require('node:assert/strict');

assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
// OK

値が深く厳密に等しい場合、message プロパティが message パラメータの値に設定された AssertionError がスローされます。message パラメータが未定義の場合、デフォルトのエラーメッセージが割り当てられます。message パラメータが Error のインスタンスである場合、AssertionError の代わりにそれがスローされます。

assert.notEqual(actual, expected[, message])#

厳格なアサーションモード

assert.notStrictEqual() のエイリアスです。

レガシーアサーションモード

安定性: 3 - 従来: 代わりに assert.notStrictEqual() を使用してください。

!= 演算子 を使用して、浅い、強制的な不等価性をテストします。NaN は特別に処理され、両側が NaN の場合は同一と見なされます。

import assert from 'node:assert';

assert.notEqual(1, 2);
// OK

assert.notEqual(1, 1);
// AssertionError: 1 != 1

assert.notEqual(1, '1');
// AssertionError: 1 != '1'const assert = require('node:assert');

assert.notEqual(1, 2);
// OK

assert.notEqual(1, 1);
// AssertionError: 1 != 1

assert.notEqual(1, '1');
// AssertionError: 1 != '1'

値が等しい場合、message プロパティが message パラメータの値に設定された AssertionError がスローされます。message パラメータが未定義の場合、デフォルトのエラーメッセージが割り当てられます。message パラメータが Error のインスタンスである場合、AssertionError の代わりにそれがスローされます。

assert.notStrictEqual(actual, expected[, message])#

Object.is() によって決定されるように、actual パラメータと expected パラメータ間の厳密な不等価性をテストします。

import assert from 'node:assert/strict';

assert.notStrictEqual(1, 2);
// OK

assert.notStrictEqual(1, 1);
// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
//
// 1

assert.notStrictEqual(1, '1');
// OKconst assert = require('node:assert/strict');

assert.notStrictEqual(1, 2);
// OK

assert.notStrictEqual(1, 1);
// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
//
// 1

assert.notStrictEqual(1, '1');
// OK

値が厳密に等しい場合、message プロパティが message パラメータの値に設定された AssertionError がスローされます。message パラメータが未定義の場合、デフォルトのエラーメッセージが割り当てられます。message パラメータが Error のインスタンスである場合、AssertionError の代わりにそれがスローされます。

assert.ok(value[, message])#

value が真偽値であるかをテストします。これは assert.equal(!!value, true, message) と同等です。

valueがtruthyでない場合、messageプロパティがmessageパラメータの値に設定されたAssertionErrorがスローされます。messageパラメータがundefinedの場合、デフォルトのエラーメッセージが割り当てられます。messageパラメータがErrorのインスタンスである場合、AssertionErrorの代わりにそれがスローされます。引数が全く渡されない場合、messageは文字列「'No value argument passed to `assert.ok()`'」に設定されます。

replでは、ファイル内でスローされるものとは異なるエラーメッセージが表示されることに注意してください!詳細は下記を参照してください。

import assert from 'node:assert/strict';

assert.ok(true);
// OK
assert.ok(1);
// OK

assert.ok();
// AssertionError: No value argument passed to `assert.ok()`

assert.ok(false, 'it\'s false');
// AssertionError: it's false

// In the repl:
assert.ok(typeof 123 === 'string');
// AssertionError: false == true

// In a file (e.g. test.js):
assert.ok(typeof 123 === 'string');
// AssertionError: The expression evaluated to a falsy value:
//
//   assert.ok(typeof 123 === 'string')

assert.ok(false);
// AssertionError: The expression evaluated to a falsy value:
//
//   assert.ok(false)

assert.ok(0);
// AssertionError: The expression evaluated to a falsy value:
//
//   assert.ok(0)const assert = require('node:assert/strict');

assert.ok(true);
// OK
assert.ok(1);
// OK

assert.ok();
// AssertionError: No value argument passed to `assert.ok()`

assert.ok(false, 'it\'s false');
// AssertionError: it's false

// In the repl:
assert.ok(typeof 123 === 'string');
// AssertionError: false == true

// In a file (e.g. test.js):
assert.ok(typeof 123 === 'string');
// AssertionError: The expression evaluated to a falsy value:
//
//   assert.ok(typeof 123 === 'string')

assert.ok(false);
// AssertionError: The expression evaluated to a falsy value:
//
//   assert.ok(false)

assert.ok(0);
// AssertionError: The expression evaluated to a falsy value:
//
//   assert.ok(0)
import assert from 'node:assert/strict';

// Using `assert()` works the same:
assert(0);
// AssertionError: The expression evaluated to a falsy value:
//
//   assert(0)const assert = require('node:assert');

// Using `assert()` works the same:
assert(0);
// AssertionError: The expression evaluated to a falsy value:
//
//   assert(0)

assert.rejects(asyncFn[, error][, message])#

asyncFnプロミスを待機します。または、asyncFnが関数の場合、関数をすぐに呼び出し、返されたプロミスが完了するのを待機します。その後、プロミスが拒否されていることを確認します。

asyncFnが関数であり、同期的にエラーをスローした場合、assert.rejects()はそのエラーを含む拒否されたPromiseを返します。関数がプロミスを返さない場合、assert.rejects()ERR_INVALID_RETURN_VALUEエラーを含む拒否されたPromiseを返します。どちらの場合も、エラーハンドラはスキップされます。

非同期的な性質に加え、完了を待つ動作はassert.throws()と全く同じです。

指定されている場合、errorClassRegExp、検証関数、各プロパティがテストされるオブジェクト、または各プロパティ(非列挙可能なmessagenameプロパティを含む)がテストされるエラーインスタンスにすることができます。

指定されている場合、messageは、asyncFnが拒否に失敗した場合にAssertionErrorによって提供されるメッセージになります。

import assert from 'node:assert/strict';

await assert.rejects(
  async () => {
    throw new TypeError('Wrong value');
  },
  {
    name: 'TypeError',
    message: 'Wrong value',
  },
);const assert = require('node:assert/strict');

(async () => {
  await assert.rejects(
    async () => {
      throw new TypeError('Wrong value');
    },
    {
      name: 'TypeError',
      message: 'Wrong value',
    },
  );
})();
import assert from 'node:assert/strict';

await assert.rejects(
  async () => {
    throw new TypeError('Wrong value');
  },
  (err) => {
    assert.strictEqual(err.name, 'TypeError');
    assert.strictEqual(err.message, 'Wrong value');
    return true;
  },
);const assert = require('node:assert/strict');

(async () => {
  await assert.rejects(
    async () => {
      throw new TypeError('Wrong value');
    },
    (err) => {
      assert.strictEqual(err.name, 'TypeError');
      assert.strictEqual(err.message, 'Wrong value');
      return true;
    },
  );
})();
import assert from 'node:assert/strict';

assert.rejects(
  Promise.reject(new Error('Wrong value')),
  Error,
).then(() => {
  // ...
});const assert = require('node:assert/strict');

assert.rejects(
  Promise.reject(new Error('Wrong value')),
  Error,
).then(() => {
  // ...
});

errorは文字列にできません。2番目の引数として文字列が提供された場合、errorは省略されたとみなされ、その文字列が代わりにmessageに使用されます。これは見落としやすいミスにつながる可能性があります。2番目の引数として文字列を使用することを検討している場合は、assert.throws()の例を注意深く読んでください。

assert.strictEqual(actual, expected[, message])#

Object.is()で決定されるように、actualパラメータとexpectedパラメータの厳密な等価性をテストします。

import assert from 'node:assert/strict';

assert.strictEqual(1, 2);
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
//
// 1 !== 2

assert.strictEqual(1, 1);
// OK

assert.strictEqual('Hello foobar', 'Hello World!');
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
// + actual - expected
//
// + 'Hello foobar'
// - 'Hello World!'
//          ^

const apples = 1;
const oranges = 2;
assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2

assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
// TypeError: Inputs are not identicalconst assert = require('node:assert/strict');

assert.strictEqual(1, 2);
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
//
// 1 !== 2

assert.strictEqual(1, 1);
// OK

assert.strictEqual('Hello foobar', 'Hello World!');
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
// + actual - expected
//
// + 'Hello foobar'
// - 'Hello World!'
//          ^

const apples = 1;
const oranges = 2;
assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2

assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
// TypeError: Inputs are not identical

値が厳密に等しくない場合、messageプロパティがmessageパラメータの値に設定されたAssertionErrorがスローされます。messageパラメータがundefinedの場合、デフォルトのエラーメッセージが割り当てられます。messageパラメータがErrorのインスタンスである場合、AssertionErrorの代わりにそれがスローされます。

assert.throws(fn[, error][, message])#

関数fnがエラーをスローすることを期待します。

指定されている場合、errorClassRegExp、検証関数、各プロパティが厳密な深層等価性についてテストされる検証オブジェクト、または各プロパティ(非列挙可能なmessagenameプロパティを含む)が厳密な深層等価性についてテストされるエラーインスタンスにすることができます。オブジェクトを使用する場合、文字列プロパティに対して検証を行う際に正規表現を使用することも可能です。例については下記を参照してください。

指定されている場合、messageは、fn呼び出しがスローに失敗した場合、またはエラー検証が失敗した場合に、AssertionErrorによって提供されるメッセージに追加されます。

カスタム検証オブジェクト/エラーインスタンス

import assert from 'node:assert/strict';

const err = new TypeError('Wrong value');
err.code = 404;
err.foo = 'bar';
err.info = {
  nested: true,
  baz: 'text',
};
err.reg = /abc/i;

assert.throws(
  () => {
    throw err;
  },
  {
    name: 'TypeError',
    message: 'Wrong value',
    info: {
      nested: true,
      baz: 'text',
    },
    // Only properties on the validation object will be tested for.
    // Using nested objects requires all properties to be present. Otherwise
    // the validation is going to fail.
  },
);

// Using regular expressions to validate error properties:
assert.throws(
  () => {
    throw err;
  },
  {
    // The `name` and `message` properties are strings and using regular
    // expressions on those will match against the string. If they fail, an
    // error is thrown.
    name: /^TypeError$/,
    message: /Wrong/,
    foo: 'bar',
    info: {
      nested: true,
      // It is not possible to use regular expressions for nested properties!
      baz: 'text',
    },
    // The `reg` property contains a regular expression and only if the
    // validation object contains an identical regular expression, it is going
    // to pass.
    reg: /abc/i,
  },
);

// Fails due to the different `message` and `name` properties:
assert.throws(
  () => {
    const otherErr = new Error('Not found');
    // Copy all enumerable properties from `err` to `otherErr`.
    for (const [key, value] of Object.entries(err)) {
      otherErr[key] = value;
    }
    throw otherErr;
  },
  // The error's `message` and `name` properties will also be checked when using
  // an error as validation object.
  err,
);const assert = require('node:assert/strict');

const err = new TypeError('Wrong value');
err.code = 404;
err.foo = 'bar';
err.info = {
  nested: true,
  baz: 'text',
};
err.reg = /abc/i;

assert.throws(
  () => {
    throw err;
  },
  {
    name: 'TypeError',
    message: 'Wrong value',
    info: {
      nested: true,
      baz: 'text',
    },
    // Only properties on the validation object will be tested for.
    // Using nested objects requires all properties to be present. Otherwise
    // the validation is going to fail.
  },
);

// Using regular expressions to validate error properties:
assert.throws(
  () => {
    throw err;
  },
  {
    // The `name` and `message` properties are strings and using regular
    // expressions on those will match against the string. If they fail, an
    // error is thrown.
    name: /^TypeError$/,
    message: /Wrong/,
    foo: 'bar',
    info: {
      nested: true,
      // It is not possible to use regular expressions for nested properties!
      baz: 'text',
    },
    // The `reg` property contains a regular expression and only if the
    // validation object contains an identical regular expression, it is going
    // to pass.
    reg: /abc/i,
  },
);

// Fails due to the different `message` and `name` properties:
assert.throws(
  () => {
    const otherErr = new Error('Not found');
    // Copy all enumerable properties from `err` to `otherErr`.
    for (const [key, value] of Object.entries(err)) {
      otherErr[key] = value;
    }
    throw otherErr;
  },
  // The error's `message` and `name` properties will also be checked when using
  // an error as validation object.
  err,
);

コンストラクタを使用したインスタンスの検証

import assert from 'node:assert/strict';

assert.throws(
  () => {
    throw new Error('Wrong value');
  },
  Error,
);const assert = require('node:assert/strict');

assert.throws(
  () => {
    throw new Error('Wrong value');
  },
  Error,
);

RegExpを使用したエラーメッセージの検証

正規表現を使用すると、エラーオブジェクトで.toStringが実行されるため、エラー名も含まれます。

import assert from 'node:assert/strict';

assert.throws(
  () => {
    throw new Error('Wrong value');
  },
  /^Error: Wrong value$/,
);const assert = require('node:assert/strict');

assert.throws(
  () => {
    throw new Error('Wrong value');
  },
  /^Error: Wrong value$/,
);

カスタムエラー検証

すべての内部検証が合格したことを示すには、関数はtrueを返す必要があります。そうでない場合は、AssertionErrorで失敗します。

import assert from 'node:assert/strict';

assert.throws(
  () => {
    throw new Error('Wrong value');
  },
  (err) => {
    assert(err instanceof Error);
    assert(/value/.test(err));
    // Avoid returning anything from validation functions besides `true`.
    // Otherwise, it's not clear what part of the validation failed. Instead,
    // throw an error about the specific validation that failed (as done in this
    // example) and add as much helpful debugging information to that error as
    // possible.
    return true;
  },
  'unexpected error',
);const assert = require('node:assert/strict');

assert.throws(
  () => {
    throw new Error('Wrong value');
  },
  (err) => {
    assert(err instanceof Error);
    assert(/value/.test(err));
    // Avoid returning anything from validation functions besides `true`.
    // Otherwise, it's not clear what part of the validation failed. Instead,
    // throw an error about the specific validation that failed (as done in this
    // example) and add as much helpful debugging information to that error as
    // possible.
    return true;
  },
  'unexpected error',
);

errorは文字列にできません。2番目の引数として文字列が提供された場合、errorは省略されたとみなされ、その文字列が代わりにmessageに使用されます。これは見落としやすいミスにつながる可能性があります。スローされたエラーメッセージと同じメッセージを使用すると、ERR_AMBIGUOUS_ARGUMENTエラーが発生します。2番目の引数として文字列を使用することを検討している場合は、以下の例を注意深く読んでください。

import assert from 'node:assert/strict';

function throwingFirst() {
  throw new Error('First');
}

function throwingSecond() {
  throw new Error('Second');
}

function notThrowing() {}

// The second argument is a string and the input function threw an Error.
// The first case will not throw as it does not match for the error message
// thrown by the input function!
assert.throws(throwingFirst, 'Second');
// In the next example the message has no benefit over the message from the
// error and since it is not clear if the user intended to actually match
// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
assert.throws(throwingSecond, 'Second');
// TypeError [ERR_AMBIGUOUS_ARGUMENT]

// The string is only used (as message) in case the function does not throw:
assert.throws(notThrowing, 'Second');
// AssertionError [ERR_ASSERTION]: Missing expected exception: Second

// If it was intended to match for the error message do this instead:
// It does not throw because the error messages match.
assert.throws(throwingSecond, /Second$/);

// If the error message does not match, an AssertionError is thrown.
assert.throws(throwingFirst, /Second$/);
// AssertionError [ERR_ASSERTION]const assert = require('node:assert/strict');

function throwingFirst() {
  throw new Error('First');
}

function throwingSecond() {
  throw new Error('Second');
}

function notThrowing() {}

// The second argument is a string and the input function threw an Error.
// The first case will not throw as it does not match for the error message
// thrown by the input function!
assert.throws(throwingFirst, 'Second');
// In the next example the message has no benefit over the message from the
// error and since it is not clear if the user intended to actually match
// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
assert.throws(throwingSecond, 'Second');
// TypeError [ERR_AMBIGUOUS_ARGUMENT]

// The string is only used (as message) in case the function does not throw:
assert.throws(notThrowing, 'Second');
// AssertionError [ERR_ASSERTION]: Missing expected exception: Second

// If it was intended to match for the error message do this instead:
// It does not throw because the error messages match.
assert.throws(throwingSecond, /Second$/);

// If the error message does not match, an AssertionError is thrown.
assert.throws(throwingFirst, /Second$/);
// AssertionError [ERR_ASSERTION]

混乱を招くエラーが発生しやすい表記法のため、2番目の引数として文字列を使用しないでください。