Node.js v25.0.0 文件
- Node.js v25.0.0
-
目錄
- Assert
- 嚴格斷言模式
- 舊式斷言模式
- 類:
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
-
索引
- 斷言測試
- 非同步上下文跟蹤
- 非同步鉤子
- 緩衝區
- C++ 外掛
- 使用 Node-API 的 C/C++ 外掛
- C++ 嵌入器 API
- 子程序
- 叢集
- 命令列選項
- 控制檯
- 加密
- 偵錯程式
- 已棄用的 API
- 診斷通道
- DNS
- 域
- 環境變數
- 錯誤
- 事件
- 檔案系統
- 全域性物件
- HTTP
- HTTP/2
- HTTPS
- 檢查器
- 國際化
- 模組:CommonJS 模組
- 模組:ECMAScript 模組
- 模組:
node:moduleAPI - 模組:包
- 模組:TypeScript
- 網路
- 作業系統
- 路徑
- 效能鉤子
- 許可權
- 程序
- Punycode
- 查詢字串
- 逐行讀取
- REPL
- 報告
- 單一可執行檔案應用
- SQLite
- 流
- 字串解碼器
- 測試執行器
- 定時器
- TLS/SSL
- 跟蹤事件
- TTY
- UDP/資料報
- URL
- 實用工具
- V8
- 虛擬機器
- WASI
- Web Crypto API
- Web Streams API
- 工作執行緒
- Zlib
- 其他版本
- 選項
Assert (斷言)#
原始碼: lib/assert.js
node:assert 模組提供了一組用於驗證不變數的斷言函式。
嚴格斷言模式#
在嚴格斷言模式下,非嚴格方法的行為與其對應的嚴格方法類似。例如,assert.deepEqual() 的行為將類似於 assert.deepStrictEqual()。
在嚴格斷言模式下,物件的錯誤訊息會顯示差異(diff)。在舊式斷言模式下,物件的錯誤訊息會顯示物件本身,且常常被截斷。
要使用嚴格斷言模式
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#
- 繼承自:<errors.Error>
表示斷言失敗。所有由 node:assert 模組丟擲的錯誤都將是 AssertionError 類的例項。
new assert.AssertionError(options)#
options<Object>
一個 <Error> 的子類,表示斷言失敗。
所有例項都包含內建的 Error 屬性(message 和 name)以及:
actual<any> 設定為諸如assert.strictEqual()等方法的actual引數。expected<any> 設定為諸如assert.strictEqual()等方法的expected值。generatedMessage<boolean> 指示訊息是自動生成的(true)還是手動提供的。code<string> 值始終為ERR_ASSERTION,以表明該錯誤是斷言錯誤。operator<string> 設定為傳入的運算子值。
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',非嚴格模式)。要在使用解構方法時保留自定義選項,請避免解構並直接在例項上呼叫方法。
assert(value[, message])#
assert.ok() 的別名。
assert.deepEqual(actual, expected[, message])#
嚴格斷言模式
舊式斷言模式
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 {}
如果值不相等,則會丟擲一個 AssertionError,其 message 屬性等於 message 引數的值。如果 message 引數未定義,則會分配一個預設的錯誤訊息。如果 message 引數是 <Error> 的例項,則會丟擲該 <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
如果值不相等,則會丟擲一個 AssertionError,其 message 屬性等於 message 引數的值。如果 message 引數未定義,則會分配一個預設的錯誤訊息。如果 message 引數是 <Error> 的例項,則會丟擲該 <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 型別,則會丟擲一個 AssertionError,其 message 屬性等於 message 引數的值。如果 message 引數未定義,則會分配一個預設的錯誤訊息。如果 message 引數是 <Error> 的例項,則會丟擲該 <Error> 例項而不是 AssertionError。
assert.doesNotReject(asyncFn[, error][, message])#
asyncFn<Function> | <Promise>error<RegExp> | <Function>message<string>- 返回:<Promise>
等待 asyncFn promise 完成,或者如果 asyncFn 是一個函式,則立即呼叫該函式並等待返回的 promise 完成。然後它將檢查該 promise 沒有被拒絕(rejected)。
如果 asyncFn 是一個函式並且它同步地丟擲一個錯誤,assert.doesNotReject() 將返回一個帶有該錯誤的被拒絕的 Promise。如果該函式不返回一個 promise,assert.doesNotReject() 將返回一個帶有 ERR_INVALID_RETURN_VALUE 錯誤的被拒絕的 Promise。在這兩種情況下,錯誤處理程式都會被跳過。
使用 assert.doesNotReject() 實際上沒什麼用,因為捕獲一個拒絕然後再次拒絕它的好處很小。相反,可以考慮在不應該拒絕的特定程式碼路徑旁邊添加註釋,並保持錯誤訊息儘可能具有表現力。
如果指定了 error,它可以是一個Class、<RegExp> 或一個驗證函式。更多詳情請參閱 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<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,
);
但是,以下程式碼將導致一個 AssertionError,其訊息為“Got unwanted exception...”(收到了不期望的異常...)。
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() 的別名。
舊式斷言模式
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 } }
如果值不相等,則會丟擲一個 AssertionError,其 message 屬性等於 message 引數的值。如果 message 引數未定義,則會分配一個預設的錯誤訊息。如果 message 引數是 <Error> 的例項,則會丟擲該 <Error> 例項而不是 AssertionError。
assert.fail([message])#
丟擲一個帶有提供的錯誤訊息或預設錯誤訊息的 AssertionError。如果 message 引數是 <Error> 的例項,則會丟擲該 <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 型別,則會丟擲一個 AssertionError,其 message 屬性等於 message 引數的值。如果 message 引數未定義,則會分配一個預設的錯誤訊息。如果 message 引數是 <Error> 的例項,則會丟擲該 <Error> 例項而不是 AssertionError。
assert.notDeepEqual(actual, expected[, message])#
嚴格斷言模式
assert.notDeepStrictEqual() 的別名。
舊式斷言模式
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
如果值是深度相等的,則會丟擲一個 AssertionError,其 message 屬性等於 message 引數的值。如果 message 引數未定義,則會分配一個預設的錯誤訊息。如果 message 引數是 <Error> 的例項,則會丟擲該 <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
如果值是深度且嚴格相等的,則會丟擲一個 AssertionError,其 message 屬性等於 message 引數的值。如果 message 引數未定義,則會分配一個預設的錯誤訊息。如果 message 引數是 <Error> 的例項,則會丟擲該 <Error> 例項而不是 AssertionError。
assert.notEqual(actual, expected[, message])#
嚴格斷言模式
舊式斷言模式
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'
如果值相等,則會丟擲一個 AssertionError,其 message 屬性等於 message 引數的值。如果 message 引數未定義,則會分配一個預設的錯誤訊息。如果 message 引數是 <Error> 的例項,則會丟擲該 <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
如果值是嚴格相等的,則會丟擲一個 AssertionError,其 message 屬性等於 message 引數的值。如果 message 引數未定義,則會分配一個預設的錯誤訊息。如果 message 引數是 <Error> 的例項,則會丟擲該 <Error> 例項而不是 AssertionError。
assert.ok(value[, message])#
測試 value 是否為真值(truthy)。它等同於 assert.equal(!!value, true, message)。
如果 value 不是真值,則會丟擲一個 AssertionError,其 message 屬性等於 message 引數的值。如果 message 引數是 undefined,則會分配一個預設的錯誤訊息。如果 message 引數是 <Error> 的例項,則會丟擲該 <Error> 例項而不是 AssertionError。如果根本沒有傳入任何引數,message 將被設定為字串:'No value argument passed to `assert.ok()`'(沒有值引數傳遞給 `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 完成,或者如果 asyncFn 是一個函式,則立即呼叫該函式並等待返回的 promise 完成。然後它將檢查該 promise 被拒絕(rejected)。
如果 asyncFn 是一個函式並且它同步地丟擲一個錯誤,assert.rejects() 將返回一個帶有該錯誤的被拒絕的 Promise。如果該函式不返回一個 promise,assert.rejects() 將返回一個帶有 ERR_INVALID_RETURN_VALUE 錯誤的被拒絕的 Promise。在這兩種情況下,錯誤處理程式都會被跳過。
除了等待完成的非同步特性外,其行為與 assert.throws() 完全相同。
如果指定了 error,它可以是一個Class、<RegExp>、一個驗證函式、一個每個屬性都會被測試的物件,或者一個每個屬性(包括不可列舉的 message 和 name 屬性)都會被測試的錯誤例項。
如果指定了 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 不能是字串。如果一個字串作為第二個引數提供,那麼 error 將被假定為省略,而該字串將用於 message。這可能導致容易忽略的錯誤。如果考慮使用字串作為第二個引數,請仔細閱讀 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
如果值不是嚴格相等的,則會丟擲一個 AssertionError,其 message 屬性等於 message 引數的值。如果 message 引數未定義,則會分配一個預設的錯誤訊息。如果 message 引數是 <Error> 的例項,則會丟擲該 <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 不能是字串。如果一個字串作為第二個引數提供,那麼 error 將被假定為省略,而該字串將用於 message。這可能導致容易忽略的錯誤。使用與丟擲的錯誤訊息相同的訊息將導致一個 ERR_AMBIGUOUS_ARGUMENT 錯誤。如果考慮使用字串作為第二個引數,請仔細閱讀下面的示例。
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]
由於這種表示法容易出錯且令人困惑,請避免使用字串作為第二個引數。
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,即使這些屬性是不可列舉的。
- 忽略稀疏陣列中的空洞(holes)。
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