When discussing chai-as-promised
, there are two ways you can handle it:
expect(promise).to.eventually.be.rejected
or:
promise.should.be.rejected
If needed, you can also use rejectedWith()
to specify the Error class/constructor.
Here's a demonstration:
mocha.setup('bdd');
mocha.checkLeaks();
let { expect } = chai;
chai.should();
let chaiAsPromised = module.exports; /* workaround for lack of UMD file, only for SO */
chai.use(chaiAsPromised);
async function foo(){
throw new Error();
}
describe('Asynchronous Function', function(){
it('Expect and Eventually', function(){
return expect(foo()).to.eventually.be.rejected;
})
it('With Should', function(){
return foo().should.be.rejected;
});
});
mocha.run();
.as-console {
display: none !important;
}
<script>
window.module = {}; function require(){ return {} }; /* workaround for lack of UMD file, only for SO */
</script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98fbf0f9f1b5f9ebb5e8eaf7f5f1ebfdfcd8afb6a9b6a9">[email protected]</a>/lib/chai-as-promised.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/9.1.1/mocha.min.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="204348414960140e130e14">[email protected]</a>/chai.js"></script>
<link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css" />
<div id="mocha"></div>