Node.js v25.0.0 ドキュメンテーション
- Node.js v25.0.0
-
目次
- Assert
- Strict アサーションモード
- Legacy アサーションモード
- クラス:
assert.AssertionError - クラス:
assert.Assert assert(value[, message])assert.deepEqual(actual, expected[, message])assert.deepStrictEqual(actual, expected[, message])assert.doesNotMatch(string, regexp[, message])assert.doesNotReject(asyncFn[, error][, message])assert.doesNotThrow(fn[, error][, message])assert.equal(actual, expected[, message])assert.fail([message])assert.ifError(value)assert.match(string, regexp[, message])assert.notDeepEqual(actual, expected[, message])assert.notDeepStrictEqual(actual, expected[, message])assert.notEqual(actual, expected[, message])assert.notStrictEqual(actual, expected[, message])assert.ok(value[, message])assert.rejects(asyncFn[, error][, message])assert.strictEqual(actual, expected[, message])assert.throws(fn[, error][, message])assert.partialDeepStrictEqual(actual, expected[, message])
- Assert
-
索引
- アサーションテスト
- 非同期コンテキストの追跡
- Async hooks
- Buffer
- C++アドオン
- Node-API を使用した C/C++ アドオン
- C++ embedder API
- 子プロセス
- Cluster
- コマンドラインオプション
- Console
- Crypto
- Debugger
- 非推奨のAPI
- Diagnostics Channel
- DNS
- Domain
- 環境変数
- エラー
- Events
- ファイルシステム
- Globals
- HTTP
- HTTP/2
- HTTPS
- Inspector
- 国際化
- モジュール: CommonJS モジュール
- モジュール: ECMAScript モジュール
- モジュール:
node:moduleAPI - モジュール: パッケージ
- モジュール: TypeScript
- Net
- OS
- Path
- Performance hooks
- パーミッション
- Process
- Punycode
- クエリストリング
- Readline
- REPL
- レポート
- 単一実行可能ファイルアプリケーション
- SQLite
- Stream
- String decoder
- テストランナー
- タイマー
- TLS/SSL
- トレースイベント
- TTY
- UDP/datagram
- URL
- ユーティリティ
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- ワーカースレッド
- Zlib
- 他のバージョン
- オプション
Assert#
ソースコード: lib/assert.js
node:assert モジュールは、不変条件を検証するための一連のアサーション関数を提供します。
Strict アサーションモード#
Strict アサーションモードでは、非 Strict メソッドは対応する Strict メソッドのように動作します。例えば、assert.deepEqual() は assert.deepStrictEqual() のように動作します。
Strict アサーションモードでは、オブジェクトのエラーメッセージには差分が表示されます。Legacy アサーションモードでは、オブジェクトのエラーメッセージにはオブジェクトそのものが表示されますが、しばしば切り詰められます。
Strict アサーションモードを使用するには
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() ドキュメントをお読みください。
Legacy アサーションモード#
Legacy アサーションモードは、以下の関数で == 演算子 を使用します。
Legacy アサーションモードを使用するには
import assert from 'node:assert';const assert = require('node:assert');
Legacy アサーションモードは、特に assert.deepEqual() を使用する場合、予期しない結果になる可能性があります。
// WARNING: This does not throw an AssertionError in legacy assertion mode!
assert.deepEqual(/a/gi, new Date());
クラス: assert.AssertionError#
- 継承元: <errors.Error>
アサーションの失敗を示します。node:assert モジュールによってスローされるすべてのエラーは、AssertionError クラスのインスタンスになります。
new assert.AssertionError(options)#
options<Object>message<string> 指定された場合、エラーメッセージはこの値に設定されます。actual<any> エラーインスタンスのactualプロパティ。expected<any> エラーインスタンスのexpectedプロパティ。operator<string> エラーインスタンスのoperatorプロパティ。stackStartFn<Function> 指定された場合、生成されるスタックトレースはこの関数より前のフレームを省略します。diff<string>'full'に設定すると、アサーションエラーで完全な差分を表示します。デフォルトは'simple'です。受け入れられる値:'simple'、'full'。
アサーションの失敗を示す <Error> のサブクラスです。
すべてのインスタンスには、組み込みの Error プロパティ (message と name) と以下が含まれます。
actual<any>assert.strictEqual()などのメソッドのactual引数に設定されます。expected<any>assert.strictEqual()などのメソッドのexpectedの値に設定されます。generatedMessage<boolean> メッセージが自動生成された (true) かどうかを示します。code<string> エラーがアサーションエラーであることを示すため、値は常にERR_ASSERTIONです。operator<string> 渡された 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.Assert#
Assert クラスを使用すると、カスタムオプションを持つ独立したアサーションインスタンスを作成できます。
new assert.Assert([options])#
options<Object>
新しいアサーションインスタンスを作成します。diff オプションは、アサーションエラーメッセージにおける差分の詳細度を制御します。
const { Assert } = require('node:assert');
const assertInstance = new Assert({ diff: 'full' });
assertInstance.deepStrictEqual({ a: 1 }, { a: 2 });
// Shows a full diff in the error message.
重要: Assert インスタンスからアサーションメソッドを分割代入すると、メソッドはインスタンスの設定オプション (diff、strict、skipPrototype 設定など) への接続を失います。分割代入されたメソッドは、代わりにデフォルトの動作にフォールバックします。
const myAssert = new Assert({ diff: 'full' });
// This works as expected - uses 'full' diff
myAssert.strictEqual({ a: 1 }, { b: { c: 1 } });
// This loses the 'full' diff setting - falls back to default 'simple' diff
const { strictEqual } = myAssert;
strictEqual({ a: 1 }, { b: { c: 1 } });
skipPrototype オプションは、すべてのディープな等価性メソッドに影響します。
class Foo {
constructor(a) {
this.a = a;
}
}
class Bar {
constructor(a) {
this.a = a;
}
}
const foo = new Foo(1);
const bar = new Bar(1);
// Default behavior - fails due to different constructors
const assert1 = new Assert();
assert1.deepStrictEqual(foo, bar); // AssertionError
// Skip prototype comparison - passes if properties are equal
const assert2 = new Assert({ skipPrototype: true });
assert2.deepStrictEqual(foo, bar); // OK
分割代入されると、メソッドはインスタンスの this コンテキストへのアクセスを失い、デフォルトのアサーション動作 (diff: 'simple', 非 strict モード) に戻ります。分割代入されたメソッドを使用する際にカスタムオプションを維持するには、分割代入を避け、インスタンス上で直接メソッドを呼び出してください。
assert(value[, message])#
assert.ok() のエイリアスです。
assert.deepEqual(actual, expected[, message])#
Strict アサーションモード
assert.deepStrictEqual() のエイリアスです。
Legacy アサーションモード
assert.deepStrictEqual() を使用してください。actual パラメータと expected パラメータ間のディープな等価性をテストします。代わりに assert.deepStrictEqual() の使用を検討してください。assert.deepEqual() は予期しない結果になる可能性があります。
ディープな等価性とは、子オブジェクトの列挙可能な「自身の」プロパティも、以下のルールによって再帰的に評価されることを意味します。
比較の詳細#
- プリミティブ値は <NaN> を除き、
==演算子で比較されます。両方が <NaN> の場合は同一として扱われます。 - オブジェクトの型タグは同じであるべきです。
- 列挙可能な「自身の」プロパティのみが考慮されます。
- <Error> の名前、メッセージ、cause、errors は、たとえ列挙可能プロパティでなくても常に比較されます。
- オブジェクトラッパーは、オブジェクトとしても、ラップ解除された値としても比較されます。
Objectのプロパティは順序不同で比較されます。- <Map> のキーと <Set> のアイテムは順序不同で比較されます。
- 再帰は、両方が異なるか、どちらかが循環参照に遭遇したときに停止します。
- 実装はオブジェクトの
[[Prototype]]をテストしません。 - <Symbol> プロパティは比較されません。
- <WeakMap>、<WeakSet>、<Promise> インスタンスは構造的には比較されません。これらが等しいとされるのは、同じオブジェクトを参照している場合のみです。異なる
WeakMap、WeakSet、またはPromiseインスタンス間の比較は、たとえ同じ内容を含んでいても、不等価という結果になります。 - <RegExp> の lastIndex、flags、source は、たとえ列挙可能プロパティでなくても常に比較されます。
次の例では、プリミティブが == 演算子を使用して比較されるため、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> の名前、メッセージ、cause、errors は、たとえ列挙可能プロパティでなくても常に比較されます。
errorsも比較されます。 - 列挙可能な自身の <Symbol> プロパティも同様に比較されます。
- オブジェクトラッパーは、オブジェクトとしても、ラップ解除された値としても比較されます。
Objectのプロパティは順序不同で比較されます。- <Map> のキーと <Set> のアイテムは順序不同で比較されます。
- 再帰は、両方が異なるか、どちらかが循環参照に遭遇したときに停止します。
- <WeakMap>、<WeakSet>、<Promise> インスタンスは構造的には比較されません。これらが等しいとされるのは、同じオブジェクトを参照している場合のみです。異なる
WeakMap、WeakSet、またはPromiseインスタンス間の比較は、たとえ同じ内容を含んでいても、不等価という結果になります。 - <RegExp> の lastIndex、flags、source は、たとえ列挙可能プロパティでなくても常に比較されます。
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 obj = {};
weakMap1.set(obj, 'value');
weakMap2.set(obj, 'value');
// Comparing different instances fails, even with same contents
assert.deepStrictEqual(weakMap1, weakMap2);
// AssertionError: Values have same structure but are not reference-equal:
//
// WeakMap {
// <items unknown>
// }
// Comparing the same instance to itself succeeds
assert.deepStrictEqual(weakMap1, weakMap1);
// OK
const weakSet1 = new WeakSet();
const weakSet2 = new WeakSet();
weakSet1.add(obj);
weakSet2.add(obj);
// Comparing different instances fails, even with same contents
assert.deepStrictEqual(weakSet1, weakSet2);
// AssertionError: Values have same structure but are not reference-equal:
// + actual - expected
//
// WeakSet {
// <items unknown>
// }
// Comparing the same instance to itself succeeds
assert.deepStrictEqual(weakSet1, weakSet1);
// OKconst 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 obj = {};
weakMap1.set(obj, 'value');
weakMap2.set(obj, 'value');
// Comparing different instances fails, even with same contents
assert.deepStrictEqual(weakMap1, weakMap2);
// AssertionError: Values have same structure but are not reference-equal:
//
// WeakMap {
// <items unknown>
// }
// Comparing the same instance to itself succeeds
assert.deepStrictEqual(weakMap1, weakMap1);
// OK
const weakSet1 = new WeakSet();
const weakSet2 = new WeakSet();
weakSet1.add(obj);
weakSet2.add(obj);
// Comparing different instances fails, even with same contents
assert.deepStrictEqual(weakSet1, weakSet2);
// AssertionError: Values have same structure but are not reference-equal:
// + actual - expected
//
// WeakSet {
// <items unknown>
// }
// Comparing the same instance to itself succeeds
assert.deepStrictEqual(weakSet1, weakSet1);
// OK
値が等しくない場合、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<Function> | <Promise>error<RegExp> | <Function>message<string>- 戻り値: <Promise>
asyncFn promise を await するか、asyncFn が関数の場合は即座に関数を呼び出して返された promise の完了を await します。その後、promise が reject されていないことをチェックします。
asyncFn が関数で同期的にエラーをスローした場合、assert.doesNotReject() はそのエラーで reject された Promise を返します。関数が promise を返さない場合、assert.doesNotReject() は ERR_INVALID_RETURN_VALUE エラーで reject された Promise を返します。どちらの場合もエラーハンドラはスキップされます。
assert.doesNotReject() を使用することは実際には有用ではありません。なぜなら、rejection をキャッチしてから再び reject することにはほとんど利点がないからです。代わりに、reject すべきでない特定のコードパスの横にコメントを追加し、エラーメッセージをできるだけ表現豊かに保つことを検討してください。
指定された場合、error は Class、<RegExp>、または検証関数にすることができます。詳細は assert.throws() を参照してください。
完了を await する非同期的な性質を除けば、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<Function>error<RegExp> | <Function>message<string>
関数 fn がエラーをスローしないことをアサートします。
assert.doesNotThrow() を使用することは実際には有用ではありません。なぜなら、エラーをキャッチしてから再スローすることに利点がないからです。代わりに、スローすべきでない特定のコードパスの横にコメントを追加し、エラーメッセージをできるだけ表現豊かに保つことを検討してください。
assert.doesNotThrow() が呼び出されると、fn 関数を即座に呼び出します。
エラーがスローされ、それが error パラメータで指定された型と同じである場合、AssertionError がスローされます。エラーが異なる型である場合、または error パラメータが未定義の場合、エラーは呼び出し元に伝播されます。
指定された場合、error は Class、<RegExp>、または検証関数にすることができます。詳細は 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])#
Strict アサーションモード
assert.strictEqual() のエイリアスです。
Legacy アサーションモード
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
assert.ifError(value)#
value<any>
value が undefined または 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])#
Strict アサーションモード
assert.notDeepStrictEqual() のエイリアスです。
Legacy アサーションモード
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])#
Strict アサーションモード
assert.notStrictEqual() のエイリアスです。
Legacy アサーションモード
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 が truthy であるかをテストします。これは 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<Function> | <Promise>error<RegExp> | <Function> | <Object> | <Error>message<string>- 戻り値: <Promise>
asyncFn promise を await するか、asyncFn が関数の場合は即座に関数を呼び出して返された promise の完了を await します。その後、promise が reject されたことをチェックします。
asyncFn が関数で同期的にエラーをスローした場合、assert.rejects() はそのエラーで reject された Promise を返します。関数が promise を返さない場合、assert.rejects() は ERR_INVALID_RETURN_VALUE エラーで reject された Promise を返します。どちらの場合もエラーハンドラはスキップされます。
完了を await する非同期的な性質を除けば、assert.throws() と同じように動作します。
指定された場合、error は Class、<RegExp>、検証関数、各プロパティがテストされるオブジェクト、または列挙不可能な message と name プロパティを含む各プロパティがテストされるエラーのインスタンスにすることができます。
指定された場合、message は、asyncFn が reject に失敗した場合に 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 パラメータが未定義の場合、デフォルトのエラーメッセージが割り当てられます。message パラメータが <Error> のインスタンスである場合、AssertionError の代わりにそれがスローされます。
assert.throws(fn[, error][, message])#
fn<Function>error<RegExp> | <Function> | <Object> | <Error>message<string>
関数 fn がエラーをスローすることを期待します。
指定された場合、error は Class、<RegExp>、検証関数、各プロパティが厳密なディープイコーリティでテストされる検証オブジェクト、または列挙不可能な message と name プロパティを含む各プロパティが厳密なディープイコーリティでテストされるエラーのインスタンスにすることができます。オブジェクトを使用する場合、文字列プロパティに対して正規表現を使用することも可能です。例については以下を参照してください。
指定された場合、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,
);
コンストラクタを使用して instanceof を検証する
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引数として文字列を使用することは避けてください。
assert.partialDeepStrictEqual(actual, expected[, message])#
actual パラメータと expected パラメータ間の部分的なディープな等価性をテストします。「ディープな」等価性とは、子オブジェクトの列挙可能な「自身の」プロパティが以下のルールによって再帰的に評価されることを意味します。「部分的な」等価性とは、expected パラメータに存在するプロパティのみが比較されることを意味します。
このメソッドは、常に assert.deepStrictEqual() と同じテストケースをパスし、そのスーパーセットとして動作します。
比較の詳細#
- プリミティブ値は
Object.is()を使用して比較されます。 - オブジェクトの型タグは同じであるべきです。
- オブジェクトの
[[Prototype]]は比較されません。 - 列挙可能な「自身の」プロパティのみが考慮されます。
- <Error> の名前、メッセージ、cause、errors は、たとえ列挙可能プロパティでなくても常に比較されます。
errorsも比較されます。 - 列挙可能な自身の <Symbol> プロパティも同様に比較されます。
- オブジェクトラッパーは、オブジェクトとしても、ラップ解除された値としても比較されます。
Objectのプロパティは順序不同で比較されます。- <Map> のキーと <Set> のアイテムは順序不同で比較されます。
- 再帰は、両方の辺が異なるか、両方の辺が循環参照に遭遇したときに停止します。
- <WeakMap>、<WeakSet>、<Promise> インスタンスは構造的には比較されません。これらが等しいとされるのは、同じオブジェクトを参照している場合のみです。異なる
WeakMap、WeakSet、またはPromiseインスタンス間の比較は、たとえ同じ内容を含んでいても、不等価という結果になります。 - <RegExp> の lastIndex、flags、source は、たとえ列挙可能プロパティでなくても常に比較されます。
- 疎な配列の穴は無視されます。
import assert from 'node:assert';
assert.partialDeepStrictEqual(
{ a: { b: { c: 1 } } },
{ a: { b: { c: 1 } } },
);
// OK
assert.partialDeepStrictEqual(
{ a: 1, b: 2, c: 3 },
{ b: 2 },
);
// OK
assert.partialDeepStrictEqual(
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[4, 5, 8],
);
// OK
assert.partialDeepStrictEqual(
new Set([{ a: 1 }, { b: 1 }]),
new Set([{ a: 1 }]),
);
// OK
assert.partialDeepStrictEqual(
new Map([['key1', 'value1'], ['key2', 'value2']]),
new Map([['key2', 'value2']]),
);
// OK
assert.partialDeepStrictEqual(123n, 123n);
// OK
assert.partialDeepStrictEqual(
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[5, 4, 8],
);
// AssertionError
assert.partialDeepStrictEqual(
{ a: 1 },
{ a: 1, b: 2 },
);
// AssertionError
assert.partialDeepStrictEqual(
{ a: { b: 2 } },
{ a: { b: '2' } },
);
// AssertionErrorconst assert = require('node:assert');
assert.partialDeepStrictEqual(
{ a: { b: { c: 1 } } },
{ a: { b: { c: 1 } } },
);
// OK
assert.partialDeepStrictEqual(
{ a: 1, b: 2, c: 3 },
{ b: 2 },
);
// OK
assert.partialDeepStrictEqual(
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[4, 5, 8],
);
// OK
assert.partialDeepStrictEqual(
new Set([{ a: 1 }, { b: 1 }]),
new Set([{ a: 1 }]),
);
// OK
assert.partialDeepStrictEqual(
new Map([['key1', 'value1'], ['key2', 'value2']]),
new Map([['key2', 'value2']]),
);
// OK
assert.partialDeepStrictEqual(123n, 123n);
// OK
assert.partialDeepStrictEqual(
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[5, 4, 8],
);
// AssertionError
assert.partialDeepStrictEqual(
{ a: 1 },
{ a: 1, b: 2 },
);
// AssertionError
assert.partialDeepStrictEqual(
{ a: { b: 2 } },
{ a: { b: '2' } },
);
// AssertionError