lib: restructure assert to become a class

PR-URL: https://github.com/nodejs/node/pull/58253
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
This commit is contained in:
Miguel Marcondes Filho 2025-08-05 11:15:02 -03:00 committed by GitHub
parent 3090def635
commit 4f5d11e6fb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 823 additions and 49 deletions

View file

@ -149,6 +149,8 @@ added: v0.1.21
* `operator` {string} The `operator` property on the error instance.
* `stackStartFn` {Function} If provided, the generated stack trace omits
frames before this function.
* `diff` {string} If set to `'full'`, shows the full diff in assertion errors. Defaults to `'simple'`.
Accepted values: `'simple'`, `'full'`.
A subclass of {Error} that indicates the failure of an assertion.
@ -215,6 +217,51 @@ try {
}
```
## Class: `assert.Assert`
<!-- YAML
added: REPLACEME
-->
The `Assert` class allows creating independent assertion instances with custom options.
### `new assert.Assert([options])`
* `options` {Object}
* `diff` {string} If set to `'full'`, shows the full diff in assertion errors. Defaults to `'simple'`.
Accepted values: `'simple'`, `'full'`.
* `strict` {boolean} If set to `true`, non-strict methods behave like their
corresponding strict methods. Defaults to `true`.
Creates a new assertion instance. The `diff` option controls the verbosity of diffs in assertion error messages.
```js
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.
```
**Important**: When destructuring assertion methods from an `Assert` instance,
the methods lose their connection to the instance's configuration options (such as `diff` and `strict` settings).
The destructured methods will fall back to default behavior instead.
```js
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 } });
```
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.
## `assert(value[, message])`
<!-- YAML