new assert.Assert([options])


  • options <Object>
    • diff <string> 如果设置为 'full',在断言错误中显示完整的差异。默认为 'simple'。 可接受的值:'simple''full'
    • strict <boolean> 如果设置为 true,非严格方法将表现得像其对应的严格方法。默认值为 true

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

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 } }); 

当方法被解构时,它们会失去对实例 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.