diff --git a/lib/assert.js b/lib/assert.js index c4f73f40071d9b..aa8df99ce97e50 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -243,21 +243,21 @@ function expectedException(actual, expected, msg) { return expected.call({}, actual) === true; } -function getActual(block) { +async function getActual(block) { if (typeof block !== 'function') { throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'block', 'Function', block); } try { - block(); + await block(); } catch (e) { return e; } } // Expected to throw an error. -assert.throws = function throws(block, error, message) { - const actual = getActual(block); +assert.throws = async function throws(block, error, message) { + const actual = await getActual(block); if (typeof error === 'string') { if (arguments.length === 3) @@ -289,8 +289,8 @@ assert.throws = function throws(block, error, message) { } }; -assert.doesNotThrow = function doesNotThrow(block, error, message) { - const actual = getActual(block); +assert.doesNotThrow = async function doesNotThrow(block, error, message) { + const actual = await getActual(block); if (actual === undefined) return; diff --git a/test/parallel/test-assert-async.js b/test/parallel/test-assert-async.js new file mode 100644 index 00000000000000..94c6bbd105dbea --- /dev/null +++ b/test/parallel/test-assert-async.js @@ -0,0 +1,42 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const promisify = require('util').promisify; +const wait = promisify(setTimeout); + +// Ensure async support for assert.throws() and assert.doesNotThrow() +/* eslint-disable prefer-common-expectserror */ + +assert.throws( + async () => { assert.fail(); }, + common.expectsError({ + code: 'ERR_ASSERTION', + type: assert.AssertionError, + message: 'Failed', + operator: undefined, + actual: undefined, + expected: undefined + }) +); + +assert.throws( + async () => { + await wait(common.platformTimeout(10)); + assert.fail(); + }, + common.expectsError({ + code: 'ERR_ASSERTION', + type: assert.AssertionError, + message: 'Failed', + operator: undefined, + actual: undefined, + expected: undefined + }) +); + +assert.doesNotThrow(async () => {}); + +assert.doesNotThrow(async () => { + await wait(common.platformTimeout(10)); + assert.fail(); +});