new assert.Assert([options])
options<Object>
创建一个新的断言实例。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 设置)的关联。被析构的方法将回退到默认行为。
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 上下文的访问,并恢复为默认的断言行为(差异:‘简单’,非严格模式)。要在使用解构方法时保持自定义选项,避免解构,直接在实例上调用方法。
【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.】