From c0dd4b5d49b63fdbbb43a4a9d37f4a693af38170 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(). 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 | 64 ++++++++++++++++++------ test/parallel/test-assert-async.js | 66 ++++++++++++++++++++++++ test/parallel/test-assert.js | 11 ++++ 4 files changed, 206 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 6728a819d3ba9e..591d26a515dc71 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -312,6 +312,43 @@ parameter is undefined, a default error message is assigned. If the `message` parameter is an instance of an [`Error`][] then it will be thrown instead of the `AssertionError`. +## 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])