From ae01f26b83b3ef7299604a658b17cf274be08f01 Mon Sep 17 00:00:00 2001 From: jorge guerrero Date: Sun, 22 Feb 2026 09:25:40 -0500 Subject: [PATCH] doc: add example for mocking functions that throw errors Add documentation example showing how to mock functions that throw errors and assert those errors using assert.throws(). Includes both ESM and CommonJS examples demonstrating how to inspect the call.error property. Fixes: https://github.com/nodejs/node/issues/52357 Signed-off-by: jorge guerrero --- doc/api/test.md | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/doc/api/test.md b/doc/api/test.md index ca485180a8fbf8..79ebfb61af786b 100644 --- a/doc/api/test.md +++ b/doc/api/test.md @@ -769,6 +769,54 @@ test('spies on an object method', (t) => { }); ``` +The following example creates a mock function that throws an error, and +asserts that the error was thrown using `assert.throws()`. It also demonstrates +how to inspect the thrown error using the mock call's `error` property. + +```mjs +import assert from 'node:assert'; +import { mock, test } from 'node:test'; + +test('mocks a function that throws an error', () => { + const fn = mock.fn(() => { + throw new Error('mock error'); + }); + + // Assert that calling the function throws + assert.throws(fn, /mock error/); + + // The error is also tracked in the mock calls + assert.strictEqual(fn.mock.callCount(), 1); + const call = fn.mock.calls[0]; + assert.strictEqual(call.error.message, 'mock error'); + assert.strictEqual(call.result, undefined); + + mock.reset(); +}); +``` + +```cjs +const assert = require('node:assert'); +const { mock, test } = require('node:test'); + +test('mocks a function that throws an error', () => { + const fn = mock.fn(() => { + throw new Error('mock error'); + }); + + // Assert that calling the function throws + assert.throws(fn, /mock error/); + + // The error is also tracked in the mock calls + assert.strictEqual(fn.mock.callCount(), 1); + const call = fn.mock.calls[0]; + assert.strictEqual(call.error.message, 'mock error'); + assert.strictEqual(call.result, undefined); + + mock.reset(); +}); +``` + ### Timers Mocking timers is a technique commonly used in software testing to simulate and