Node.js Reference ยท util, assert and the Test Runner
Node.js assert.rejects() method
Reference for assert.rejects() in Node.js: await a promise or async function and check that it rejects, validating the error like assert.throws() does.
assert.rejects(asyncFnOrPromise, [error], [message]) is the asynchronous sibling of assert.throws(). It returns a promise that resolves when the given promise rejects (and the rejection matches the optional validation), and rejects with an AssertionError when the promise resolves instead.
You can pass a promise or a function that returns one. Passing a function is safer: if that function throws synchronously before returning a promise, the failure is reported properly. Always await the result, otherwise the check runs unobserved and a failure becomes an unhandled rejection.
import assert from "node:assert/strict"; await assert.rejects(async () => { throw new Error("no"); }, /no/);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
assert.rejects(asyncFn: Promise | (() => Promise), error?: Function | RegExp | object | Error | ((e: unknown) => boolean), message?: string): Promise<void> assert.doesNotReject(asyncFn: Promise | (() => Promise), error?: Function | RegExp, message?: string): Promise<void>
| Name | Description |
|---|---|
asyncFn |
A promise, or a function returning a promise, that should reject. |
error |
Optional validation of the rejection reason, with the same forms as assert.throws(). |
message |
Optional text used when the promise does not reject. |
Returns: a promise for undefined.
Errors: the returned promise rejects with an AssertionError (operator "rejects") when asyncFn resolves ("Missing expected rejection") or when the reason does not match. If a function does not return a promise, it rejects with ERR_INVALID_RETURN_VALUE.
Usage notes
- Await it. Without
await(or returning the promise from the test), a failed assertion is not seen by the test. - A function argument is called for you, so a synchronous throw inside it counts as a failure of the setup, not as the expected rejection.
- The validation forms are the same as for
assert.throws(): class, regex, object of properties, function, or error instance. - Only the rejection reason is checked. Use
assert.deepStrictEqual()separately for the values of successful calls. assert.doesNotReject()is rarely needed; awaiting the promise directly fails the test with a clearer stack trace.