I want to test a function returning a promise.
In this particular test, the promise is expected to be rejected with an Error object containing the classical message
field (in this test, it is expected to equal "my error message"
) and a custom field I added named code
, which is a string (like "EACCESS", "ERIGHT", etc, in this test it is expected to equal "EFOO"
)
I want to use chai-as-promised for that.
return expect(foo()).to.eventually.be.rejectedWith("my error message");
This assertion is working but now I would like to test the code
field too.
How to do that?
If you're using Chai-As-Promised (as you say you are), then it allows for chaining off of rejectedWith
- and it sets the chain assertion object to be the error object - meaning anything after rejectedWith()
is now going to assert on the Error. This lets you do cool things like:
return expect(foo()).to.eventually
.be.rejectedWith("my error message")
.and.be.an.instanceOf(Error)
.and.have.property('code', 'EFOO');
Some of the chai methods also chain, so you can use that to make some quite deeply nested assertions about the error:
return expect(foo()).to.eventually
.be.rejectedWith("my error message")
.and.have.property('stack')
.that.includes('myfile.js:30')