Node.js v21.7.2 文件
- Node.js v21.7.2
-
► 目錄
- Assert
- 嚴格斷言模式
- 舊版斷言模式
- 類別:assert.AssertionError
- 類別:
assert.CallTracker
assert(value[, message])
assert.deepEqual(actual, expected[, message])
assert.deepStrictEqual(actual, expected[, message])
assert.doesNotMatch(字串, 正則表達式[, 訊息])
assert.doesNotReject(非同步函數[, 錯誤][, 訊息])
assert.doesNotThrow(函數[, 錯誤][, 訊息])
assert.equal(實際, 預期[, 訊息])
assert.fail([訊息])
assert.fail(實際, 預期[, 訊息[, 運算子[, 堆疊起始函數]]])
assert.ifError(值)
assert.match(字串, 正則表達式[, 訊息])
assert.notDeepEqual(實際, 預期[, 訊息])
assert.notDeepStrictEqual(實際, 預期[, 訊息])
assert.notEqual(實際, 預期[, 訊息])
assert.notStrictEqual(實際, 預期[, 訊息])
assert.ok(值[, 訊息])
assert.rejects(非同步函數[, 錯誤][, 訊息])
assert.strictEqual(實際, 預期[, 訊息])
assert.throws(函數[, 錯誤][, 訊息])
- Assert
-
► 索引
- 斷言測試
- 非同步背景追蹤
- 非同步掛鉤
- Buffer
- C++ 外掛程式
- 使用 Node-API 的 C/C++ 外掛程式
- C++ 嵌入式 API
- 子程序
- 叢集
- 命令列選項
- 主控台
- Corepack
- 加密
- 偵錯器
- 已棄用的 API
- 診斷頻道
- DNS
- 網域
- 錯誤
- 事件
- 檔案系統
- 全域變數
- HTTP
- HTTP/2
- HTTPS
- 檢查器
- 國際化
- 模組:CommonJS 模組
- 模組:ECMAScript 模組
- 模組:
node:module
API - 模組:套件
- 網路
- 作業系統
- 路徑
- 效能掛鉤
- 權限
- 程序
- Punycode
- 查詢字串
- Readline
- REPL
- 報告
- 單一可執行應用程式
- 串流
- 字串解碼器
- 測試執行器
- 計時器
- TLS/SSL
- 追蹤事件
- TTY
- UDP/資料報
- URL
- 公用程式
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- 工作執行緒
- Zlib
- ► 其他版本
- ► 選項
斷言#
原始碼: 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
<Object>message
<string>如果提供,錯誤訊息會設定為此值。actual
<any>錯誤執行個體上的actual
屬性。expected
<any>錯誤執行個體上的expected
屬性。operator
<string>錯誤執行個體上的operator
屬性。stackStartFn
<Function>如果提供,產生的堆疊追蹤會略過此函式之前的框架。
Error
的子類別,表示斷言失敗。
所有執行個體都包含內建 Error
屬性(message
和 name
),以及
actual
<any>設定為方法(例如assert.strictEqual()
)的actual
參數。expected
<any> 設定為方法的expected
值,例如assert.strictEqual()
。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.CallTracker
#
此功能已標示為不建議使用,且將在未來版本中移除。請考慮使用其他替代方案,例如 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
<Function> 預設:非操作函式。exact
<number> 預設值:1
。- 傳回:<Function> 包裝
fn
的函式。
包裝函式預期會被呼叫 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)
#
-
fn
<Function> -
傳回:<Array> 陣列,其中包含已追蹤函式的所有呼叫。
-
物件 <Object>
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()
傳回的包裝函式資訊。 - 物件 <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
<函式> 要重設的追蹤函式。
重設呼叫追蹤器的呼叫。如果傳遞追蹤函式作為引數,則會重設呼叫。如果未傳遞引數,則會重設所有追蹤函式。
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()
的別名。
舊版斷言模式
assert.deepStrictEqual()
。測試 actual
和 expected
參數之間的深度相等性。考慮改用 assert.deepStrictEqual()
。assert.deepEqual()
可能會產生令人意外的結果。
深度相等性表示子物件的可列舉「自有」屬性也會根據下列規則遞迴評估。
比較詳細資料#
- 基本值使用
==
运算符 进行比较,但NaN
除外。如果两边都是NaN
,则视为相同。 - 对象的 类型标签 应相同。
- 仅考虑 可枚举的“自身”属性。
Error
名称和消息始终进行比较,即使这些不是可枚举属性。- 对象包装器 既作为对象又作为未包装值进行比较。
Object
属性按无序方式进行比较。Map
键和Set
项按无序方式进行比较。- 当两边不同或两边遇到循环引用时,递归停止。
- 实现不会测试对象的
[[Prototype]]
。 Symbol
属性不进行比较。WeakMap
和WeakSet
比较不依赖于其值。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
的实例,则会引发该实例,而不是 AssertionError
。
assert.deepStrictEqual(actual, expected[, message])
#
測試 actual
和 expected
參數之間的深度相等性。「深度」相等性表示子物件的可列舉「自身」屬性也會根據下列規則遞迴評估。
比較詳細資料#
- 基本值會使用
Object.is()
進行比較。 - 对象的 类型标签 应相同。
- 物件的
[[Prototype]]
會使用===
算子 進行比較。 - 仅考虑 可枚举的“自身”属性。
Error
名称和消息始终进行比较,即使这些不是可枚举属性。- 可列舉的自身
Symbol
屬性也會進行比較。 - 对象包装器 既作为对象又作为未包装值进行比较。
Object
属性按无序方式进行比较。Map
键和Set
项按无序方式进行比较。- 当两边不同或两边遇到循环引用时,递归停止。
WeakMap
和WeakSet
比較不依賴其值。請參閱下方以取得進一步詳細資料。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 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
// }
如果值不相等,則會擲回一個 AssertionError
,其 message
屬性設定為等於 message
參數的值。如果 message
參數未定義,則會指定預設錯誤訊息。如果 message
參數是 Error
的執行個體,則會擲回該執行個體,而不是 AssertionError
。
assert.doesNotMatch(字串, 正規表示法[, 訊息])
#
預期 字串
輸入不符合正規表示法。
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/);
// OK
const 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
如果值符合,或如果 字串
參數的類型不是 字串
,則會擲回 訊息
屬性設定為等於 訊息
參數值的 AssertionError
。如果 訊息
參數未定義,則會指派預設錯誤訊息。如果 訊息
參數是 Error
的執行個體,則會擲回它,而不是 AssertionError
。
assert.doesNotReject(非同步函數[, 錯誤][, 訊息])
#
等待 非同步函數
承諾或,如果 非同步函數
是函數,則立即呼叫函數並等待傳回的承諾完成。然後它會檢查承諾是否未被拒絕。
如果 asyncFn
是函式且同步擲回錯誤,assert.doesNotReject()
將傳回包含該錯誤的已拒絕 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>錯誤
<正規表示法> | <函數>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: Whoops
const 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
的執行個體,則會擲回該執行個體,而不是 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 array
const 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.fail()
是可行的,但已不建議使用。請參閱下方以取得更多詳細資訊。
assert.fail(actual, expected[, message[, operator[, stackStartFn]]])
#
assert.fail([message])
或其他 assert 函式。actual
<any>expected
<any>message
<字串> | <錯誤>operator
<string> 預設值:'!='
stackStartFn
<Function> 預設值:assert.fail
如果 message
為假值,錯誤訊息會設定為 actual
和 expected
的值,並以提供的 operator
分隔。如果只提供 actual
和 expected
這兩個參數,operator
會預設為 '!='
。如果 message
提供為第三個參數,它會用作錯誤訊息,而其他參數會儲存在拋出的物件的屬性中。如果提供 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 array
const 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
在最後三種情況下,actual
、expected
和 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)
#
值
<任何>
如果 值
不是 未定義
或 null
,則擲出 值
。這在測試 callback 中的 錯誤
參數時很有用。堆疊追蹤包含傳遞給 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 errorFrame
const 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(字串, 正規表示式[, 訊息])
#
預期 字串
輸入與正規表示式相符。
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/);
// OK
const 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
如果值不符,或者 字串
參數的類型不是 字串
,則會擲出 AssertionError
,並將 訊息
屬性設定為等於 訊息
參數的值。如果 訊息
參數未定義,則會指定預設錯誤訊息。如果 訊息
參數是 Error
的執行個體,則會擲出該執行個體,而不是 AssertionError
。
assert.notDeepEqual(實際, 預期[, 訊息])
#
嚴格斷言模式
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);
// OK
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.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
,並將 訊息
屬性設定為等於 訊息
參數的值。如果 訊息
參數未定義,則會指定預設錯誤訊息。如果 訊息
參數是 Error
的執行個體,則會擲出該執行個體,而不是 AssertionError
。
assert.notDeepStrictEqual(實際, 預期[, 訊息])
#
深度嚴格不等測試。與 assert.deepStrictEqual()
相反。
import assert from 'node:assert/strict';
assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
// OK
const assert = require('node:assert/strict');
assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
// OK
如果值深度嚴格相等,則會擲出 AssertionError
,其 message
屬性設定為等於 message
參數的值。如果 message
參數未定義,則會指定預設錯誤訊息。如果 message
參數是 Error
的實例,則會擲出該實例,而不是 AssertionError
。
assert.notEqual(actual, expected[, message])
#
嚴格斷言模式
assert.notStrictEqual()
的別名。
舊版斷言模式
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
的實例,則會擲出該實例,而不是 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');
// OK
const 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
不是真值,則會擲出 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()
會傳回一個被拒絕的 Promise
,其中包含 ERR_INVALID_RETURN_VALUE
錯誤。在兩種情況下,錯誤處理常式都會被略過。
除了等待完成的非同步本質,行為與 assert.throws()
相同。
如果已指定,error
可以是 Class
、RegExp
、驗證函式、每個屬性都將被測試的物件,或錯誤實例,其中每個屬性都將被測試,包括不可列舉的 message
和 name
屬性。
如果已指定,message
將是 AssertionError
提供的訊息,如果 asyncFn
拒絕拒絕。
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 identical
const 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
屬性)。使用物件時,在針對字串屬性驗證時,也可以使用正規表示式。請參閱下方範例。
如果指定,如果 fn
呼叫未擲回或錯誤驗證失敗,message
將附加到 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]
由於混淆且容易出錯的表示法,請避免將字串作為第二個引數。