Skip to content

Commit d428341

Browse files
committed
docs: add example for mocking functions that throw
Add documentation explaining how to mock functions that throw errors and validate them using assert.throws(). Includes examples showing how mock tracks both successful calls and thrown errors. PR-URL: #52358 Refs: #52357
1 parent ac041a2 commit d428341

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

doc/api/test.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -925,6 +925,69 @@ test('mocks setTimeout to be executed synchronously without having to actually w
925925
});
926926
```
927927

928+
### Mocking functions that throw
929+
930+
The mock function API allows mocking functions that throw errors and validating
931+
them using `assert.throws()`. This is useful for testing error handling code paths.
932+
933+
```mjs
934+
import assert from 'node:assert';
935+
import { mock, test } from 'node:test';
936+
937+
test('mocks a function that throws', () => {
938+
const fn = mock.fn(() => {
939+
throw new Error('mock error');
940+
});
941+
942+
// The function throws when called
943+
assert.throws(() => fn(), { message: 'mock error' });
944+
});
945+
```
946+
947+
```cjs
948+
const assert = require('node:assert');
949+
const { mock, test } = require('node:test');
950+
951+
test('mocks a function that throws', () => {
952+
const fn = mock.fn(() => {
953+
throw new Error('mock error');
954+
});
955+
956+
// The function throws when called
957+
assert.throws(() => fn(), { message: 'mock error' });
958+
});
959+
```
960+
961+
When using the spy functionality, the mock tracks both successful calls and
962+
thrown errors:
963+
964+
```mjs
965+
import assert from 'node:assert';
966+
import { mock, test } from 'node:test';
967+
968+
test('mocks track both results and errors', () => {
969+
let callCount = 0;
970+
const fn = mock.fn(() => {
971+
callCount++;
972+
if (callCount === 2) {
973+
throw new Error('error on second call');
974+
}
975+
return 'success';
976+
});
977+
978+
// First call succeeds
979+
assert.strictEqual(fn(), 'success');
980+
981+
// Second call throws
982+
assert.throws(() => fn(), { message: 'error on second call' });
983+
984+
// Check mock metadata
985+
assert.strictEqual(fn.mock.callCount(), 2);
986+
assert.strictEqual(fn.mock.calls[0].result, 'success');
987+
assert.strictEqual(fn.mock.calls[1].error.message, 'error on second call');
988+
});
989+
```
990+
928991
### Dates
929992

930993
The mock timers API also allows the mocking of the `Date` object. This is a

0 commit comments

Comments
 (0)