From 76f470334e2d29e69e7fa3e58e1c14106740681f Mon Sep 17 00:00:00 2001 From: cjihrig Date: Wed, 1 Jan 2025 13:18:47 -0500 Subject: [PATCH 1/2] test_runner: add assert.register() API This commit adds a top level assert.register() API to the test runner. This function allows users to define their own custom assertion functions on the TestContext. Fixes: https://github.com/nodejs/node/issues/52033 --- doc/api/test.md | 20 ++++++ lib/internal/test_runner/assert.js | 50 +++++++++++++++ lib/internal/test_runner/test.js | 52 ++++++--------- lib/test.js | 20 ++++++ .../parallel/test-runner-custom-assertions.js | 63 +++++++++++++++++++ 5 files changed, 171 insertions(+), 34 deletions(-) create mode 100644 lib/internal/test_runner/assert.js create mode 100644 test/parallel/test-runner-custom-assertions.js diff --git a/doc/api/test.md b/doc/api/test.md index 7deac4fae1efdf..ea35e5f0681c3d 100644 --- a/doc/api/test.md +++ b/doc/api/test.md @@ -1750,6 +1750,26 @@ describe('tests', async () => { }); ``` +## `assert` + + + +An object whose methods are used to configure available assertions on the +`TestContext` objects in the current process. It is possible to apply the same +configuration to all files by placing common configuration code in a module +preloaded with `--require` or `--import`. + +### `assert.register(name, fn)` + + + +Defines a new assertion function with the provided name and function. If an +assertion already exists with the same name, it is overwritten. + ## `snapshot` An object whose methods are used to configure available assertions on the -`TestContext` objects in the current process. It is possible to apply the same -configuration to all files by placing common configuration code in a module +`TestContext` objects in the current process. The methods from `node:assert` +and snapshot testing functions are available by default. + +It is possible to apply the same configuration to all files by placing common +configuration code in a module preloaded with `--require` or `--import`. ### `assert.register(name, fn)` diff --git a/lib/test.js b/lib/test.js index 99408c7501d4fe..d6a313cd0763eb 100644 --- a/lib/test.js +++ b/lib/test.js @@ -62,22 +62,14 @@ ObjectDefineProperty(module.exports, 'snapshot', { }, }); -let lazyAssert; - ObjectDefineProperty(module.exports, 'assert', { __proto__: null, configurable: true, enumerable: true, get() { - if (lazyAssert === undefined) { - const { register } = require('internal/test_runner/assert'); - - lazyAssert = { - __proto__: null, - register, - }; - } - - return lazyAssert; + const { register } = require('internal/test_runner/assert'); + const assert = { __proto__: null, register }; + ObjectDefineProperty(module.exports, 'assert', assert); + return assert; }, });