What nicholaswmin mentioned is indeed accurate, however, there is a crucial "rest of the owl" moment that I would like to clarify.
If you are thinking: "I want to ensure rejection," meaning "I want to verify that this code rejects correctly," the process is a bit intricate.
To begin with, include return fxnWhichReturnsPromise()
. The test will not pass if your function is rejecting, and you actually want it to fail under those circumstances. You must utilize the two-argument form of .then()
, which appears as follows:
.then(onFulfillCallback, onRejectCallback)
. This is necessary because if you separate it into
.then
and
.catch
, failing in the
.then
block will be captured by the subsequent
.catch
block. Consequently, what should be a failed test (as it did not reject) will actually show as passing.
In practical application, the whole setup looks similar to this:
it('rejects when given foobar', () => {
return fxnThatShouldReject(foobar)
.then(
(val) => { assert.fail(`Should have rejected, but instead returned ${val}`)
,
(err) => { assert.equal(err.message, "The expected reason for rejection") }
)
})
The reason why the assertion library lacks a pre-defined handler for this scenario is because being able to temporarily pause asynchronous execution within the test suite is essentially a feature of the test-runner. In contrast, assert.throws()
operates synchronously.