From d659f361fe002712a82a3dc7500f2ce375966329 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Guilherme=20Ara=C3=BAjo?= Date: Fri, 9 Oct 2026 14:52:49 -0300 Subject: [PATCH] test_runner: add mockReturnValue and promise helpers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add mockReturnValue(), mockResolvedValue() and mockRejectedValue() to MockFunctionContext as shorthands for common mockImplementation() patterns. Signed-off-by: Guilherme Araújo --- doc/api/test.md | 63 +++++++++++++++++++++++++++ lib/internal/test_runner/mock/mock.js | 26 +++++++++++ test/parallel/test-runner-mocking.js | 36 +++++++++++++++ 3 files changed, 125 insertions(+) diff --git a/doc/api/test.md b/doc/api/test.md index a2c98388fa4f..84947e2a3432 100644 --- a/doc/api/test.md +++ b/doc/api/test.md @@ -2464,6 +2464,69 @@ test('changes a mock behavior once', (t) => { }); ``` +### `ctx.mockRejectedValue(reason)` + + + +* `reason` {any} The value the returned promise rejects with. + +Changes the mock's implementation to a function that returns a promise rejected +with `reason`. This is shorthand for +`ctx.mockImplementation(() => Promise.reject(reason))`. + +```js +test('mocks a rejected value', async (t) => { + const fn = t.mock.fn(); + + fn.mock.mockRejectedValue(new Error('boom')); + await assert.rejects(fn(), { message: 'boom' }); +}); +``` + +### `ctx.mockResolvedValue(value)` + + + +* `value` {any} The value the returned promise resolves with. + +Changes the mock's implementation to a function that returns a promise resolved +with `value`. This is shorthand for +`ctx.mockImplementation(() => Promise.resolve(value))`. + +```js +test('mocks a resolved value', async (t) => { + const fn = t.mock.fn(); + + fn.mock.mockResolvedValue(42); + assert.strictEqual(await fn(), 42); +}); +``` + +### `ctx.mockReturnValue(value)` + + + +* `value` {any} The value returned by the mock. + +Changes the mock's implementation to a function that returns `value`. This is +shorthand for `ctx.mockImplementation(() => value)`. + +```js +test('mocks a return value', (t) => { + const fn = t.mock.fn(); + + fn.mock.mockReturnValue(42); + assert.strictEqual(fn(), 42); + assert.strictEqual(fn(), 42); +}); +``` + ### `ctx.resetCalls()`