I\'m struggling to work out the best way to verify that a promise is rejected in a Mocha test while using async/await.
Here\'s an example that works, but I dislike t
npm i chai-as-promised -D
)import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);
const expect = chai.expect;
describe('MY_DESCR', () => {
it('MY_TEST', async () => {
expect(myAsyncFunctionThatWillReject()).to.eventually.be.rejected;
});
});
You can use async/await
and should
for simple verification
it('should not throw an error', async () => {
try {
let r = await wins();
r.should.equal('Winner');
} catch (error) {
error.should.be.null(); //should.not.exist(error) can also be used
}
});
it('throws an error', async () => {
try {
await fails();
} catch (error) {
error.should.be.Error();
error.should.have.value("message", "Contrived Error");
}
});
you can write a function to swap resolve & reject handler, and do anything normally
const promise = new Promise((resolve, rejects) => {
YourPromise.then(rejects, resolve);
})
const res = await promise;
res.should.be.an("error");
A no dependency on anything but Mocha example.
Throw a known error, catch all errors, and only rethrow the known one.
it('should throw an error', async () => {
try {
await myFunction()
throw new Error('Expected error')
} catch (e) {
if (e.message && e.message === 'Expected error') throw e
}
})
If you test for errors often, wrap the code in a custom it
function.
function itThrows(message, handler) {
it(message, async () => {
try {
await handler()
throw new Error('Expected error')
} catch (e) {
if (e.message && e.message === 'Expected error') throw e
}
})
}
Then use it like this:
itThrows('should throw an error', async () => {
await myFunction()
})
I have came with this solution:
import { assert, expect, use } from "chai";
import * as chaiAsPromised from "chai-as-promised";
describe("using chaiAsPromised", () => {
it("throws an error", async () => {
await expect(await fails()).to.eventually.be.rejected;
});
});