Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions doc/api/test.md
Original file line number Diff line number Diff line change
Expand Up @@ -925,6 +925,69 @@ test('mocks setTimeout to be executed synchronously without having to actually w
});
```

### Mocking functions that throw

The mock function API allows mocking functions that throw errors and validating
them using `assert.throws()`. This is useful for testing error handling code paths.

```mjs
import assert from 'node:assert';
import { mock, test } from 'node:test';

test('mocks a function that throws', () => {
const fn = mock.fn(() => {
throw new Error('mock error');
});

// The function throws when called
assert.throws(() => fn(), { message: 'mock error' });
});
```

```cjs
const assert = require('node:assert');
const { mock, test } = require('node:test');

test('mocks a function that throws', () => {
const fn = mock.fn(() => {
throw new Error('mock error');
});

// The function throws when called
assert.throws(() => fn(), { message: 'mock error' });
});
```

When using the spy functionality, the mock tracks both successful calls and
thrown errors:

```mjs
import assert from 'node:assert';
import { mock, test } from 'node:test';

test('mocks track both results and errors', () => {
let callCount = 0;
const fn = mock.fn(() => {
callCount++;
if (callCount === 2) {
throw new Error('error on second call');
}
return 'success';
});

// First call succeeds
assert.strictEqual(fn(), 'success');

// Second call throws
assert.throws(() => fn(), { message: 'error on second call' });

// Check mock metadata
assert.strictEqual(fn.mock.callCount(), 2);
assert.strictEqual(fn.mock.calls[0].result, 'success');
assert.strictEqual(fn.mock.calls[1].error.message, 'error on second call');
});
```

### Dates

The mock timers API also allows the mocking of the `Date` object. This is a
Expand Down
4 changes: 4 additions & 0 deletions lib/internal/test_runner/reporter/dot.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ module.exports = async function* dot(source) {
yield `${colors.red}X${colors.reset}`;
ArrayPrototypePush(failedTests, data);
}
if (type === 'test:diagnostic') {
const levelColor = data.level === 'error' ? colors.red : data.level === 'warning' ? colors.yellow : colors.white;
yield `\n${levelColor}${data.message}${colors.reset}\n`;
}
if ((type === 'test:fail' || type === 'test:pass') && ++count === columns) {
yield '\n';

Expand Down