From 3babc5bb533d94e6355d062233fbe05744603115 Mon Sep 17 00:00:00 2001 From: feugy Date: Fri, 12 Jan 2018 00:16:41 +0100 Subject: [PATCH] assert: add rejects() and doesNotReject() Implement asynchronous equivalent for assert.throws() and assert.doesNotThrow(). Backport-PR-URL: https://github.com/nodejs/node/pull/24019 PR-URL: https://github.com/nodejs/node/pull/18023 Reviewed-By: James M Snell Reviewed-By: Shingo Inoue Reviewed-By: Joyee Cheung Reviewed-By: Ruben Bridgewater --- doc/api/assert.md | 80 ++++++++++++++++++++++++++++++ lib/assert.js | 65 ++++++++++++++++++------ test/parallel/test-assert-async.js | 66 ++++++++++++++++++++++++ test/parallel/test-assert.js | 11 ++++ 4 files changed, 207 insertions(+), 15 deletions(-) create mode 100644 test/parallel/test-assert-async.js diff --git a/doc/api/assert.md b/doc/api/assert.md index dbd32096b5c096..6cc3cd561eb8ef 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -242,6 +242,43 @@ If the values are not equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default error message is assigned. +## assert.doesNotReject(block[, error][, message]) + +* `block` {Function} +* `error` {RegExp|Function} +* `message` {any} + +Awaits for the promise returned by function `block` to complete and not be +rejected. See [`assert.rejects()`][] for more details. + +When `assert.doesNotReject()` is called, it will immediately call the `block` +function, and awaits for completion. + +Besides the async nature to await the completion behaves identical to +[`assert.doesNotThrow()`][]. + +```js +(async () => { + await assert.doesNotReject( + async () => { + throw new TypeError('Wrong value'); + }, + SyntaxError + ); +})(); +``` + +```js +assert.doesNotReject( + () => Promise.reject(new TypeError('Wrong value')), + SyntaxError +).then(() => { + // ... +}); +``` + ## assert.doesNotThrow(block[, error][, message]) +* `block` {Function} +* `error` {RegExp|Function|Object} +* `message` {any} + +Awaits for promise returned by function `block` to be rejected. + +When `assert.rejects()` is called, it will immediately call the `block` +function, and awaits for completion. + +Besides the async nature to await the completion behaves identical to +[`assert.throws()`][]. + +If specified, `error` can be a constructor, [`RegExp`][], a validation +function, or an object where each property will be tested for. + +If specified, `message` will be the message provided by the `AssertionError` if +the block fails to reject. + +```js +(async () => { + await assert.rejects( + async () => { + throw new Error('Wrong value'); + }, + Error + ); +})(); +``` + +```js +assert.rejects( + () => Promise.reject(new Error('Wrong value')), + Error +).then(() => { + // ... +}); +``` + ## assert.throws(block[, error][, message])