Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test a rejection with Chai as promised

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?

like image 509
Guid Avatar asked Mar 31 '15 07:03

Guid


People also ask

How do you assert Promise reject?

You can chain promises with await if you choose to. function generateException() { return new Promise(reject => { return reject(new Error('Promise Rejected'); }) it('should give an error', async ()=> { await generateException(). catch(error => { expect(error. message).to.

What is chai as promised?

Chai as Promised is an extension of that library specifically made to handle assertions with promises (as opposed to resolving them manually yourself).

What is chai used for in testing?

Chai is an assertion library that is often used alongside Mocha. It provides functions and methods that help you compare the output of a certain test with its expected value. Chai provides clean syntax that almost reads like English!


2 Answers

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') 
like image 85
Keithamus Avatar answered Sep 22 '22 22:09

Keithamus


Having version 5.1.0 of ChaiAsPromised, solution from Keithamus did not work for me - rejectedWith did not gave me the error object to assert, but "rejected" did:

return expect(foo())     .to.be.rejected     .and.be.an.instanceOf(Error)     .and.have.property('code', 'EFOO'); 

For asserting multiple properties

return expect(foo())     .to.be.rejected     .then(function(error) {         expect(error).to.have.property('name', 'my error message');         expect(error).to.have.property('code', 'EFOO');     }); 
like image 41
Markko Paas Avatar answered Sep 23 '22 22:09

Markko Paas