Assertions
assert.rejects()
Checks a rejected promise or the promise returned by a function. Await the assertion so a failed assertion belongs to the test lifecycle. Match an error type or code rather than brittle full messages. Tested on Node.js 22.16.0. Example output (one line per entry): ["matched", "ERR_ASSERTION"].
Formal Syntax & Structure
nodejs syntaxnodejs
assert.rejects(asyncFn[, error][, message])Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| asyncFn | Function | Promise | Asynchronous operation. |
| error | RegExp | Function | object | Expected rejection matcher. |
| message | string | Error | Failure detail. |
Return Value
Promise<void>
Fulfills when the rejection matches.
Working Example
Example Snippetnodejs
import assert from 'node:assert/strict';await assert.rejects(async () => { throw new RangeError('limit'); }, RangeError);console.log('matched');try { await assert.rejects(Promise.resolve(1));}catch (e) { console.log(e.code);}