new assert.Assert([options])


  • options <Object>
    • diff <string> 如果设置为 'full',在断言错误中显示完整的差异。默认为 'simple'。 可接受的值:'simple''full'
    • strict <boolean> 如果设置为 true,非严格方法将表现得像其对应的严格方法。默认值为 true
    • skipPrototype <boolean> 如果设置为 true,在深度相等检查中将跳过原型和构造函数的比较。默认值为 false

创建一个新的断言实例。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 实例中析构断言方法时,这些方法将失去与实例配置选项(例如 diffstrictskipPrototype 设置)的关联。被析构的方法将回退到默认行为。

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.】