new assert.Assert([options])
-
options
<Object>-
diff
<string> 如果设置为'full'
,则显示断言错误的完整差异。默认为'simple'
。可接受的值:'simple'
,'full'
.¥
diff
<string> If set to'full'
, shows the full diff in assertion errors. Defaults to'simple'
. Accepted values:'simple'
,'full'
. -
strict
<boolean> 如果设置为true
,则非严格方法的行为与其对应的严格方法相同。默认为true
。¥
strict
<boolean> If set totrue
, non-strict methods behave like their corresponding strict methods. Defaults totrue
. -
skipPrototype
<boolean> 如果设置为true
,则在深度相等性检查中跳过原型和构造函数比较。默认为false
。¥
skipPrototype
<boolean> If set totrue
, skips prototype and constructor comparison in deep equality checks. Defaults tofalse
.
-
创建一个新的断言实例。diff
选项控制断言错误消息中 diff 的详细程度。
¥Creates a new assertion instance. The diff
option controls the verbosity of diffs in assertion error messages.
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
设置)的连接。解构方法将恢复为默认行为。
¥Important: When destructuring assertion methods from an Assert
instance,
the methods lose their connection to the instance's configuration options (such
as diff
, strict
, and skipPrototype
settings).
The destructured methods will fall back to default behavior instead.
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
选项会影响所有深度相等方法:
¥The skipPrototype
option affects all deep equality methods:
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
上下文的访问权限,并恢复为默认断言行为(区别:'simple',非严格模式)。为了在使用解构方法时保留自定义选项,请避免解构,而应直接在实例上调用方法。
¥When destructured, methods lose access to the instance's this
context and revert to default assertion behavior
(diff: 'simple', non-strict mode).
To maintain custom options when using destructured methods, avoid
destructuring and call methods directly on the instance.