Testing for specific properties of rejected promises, with Mocha and Chai-as-Promised

旧城冷巷雨未停 提交于 2019-11-30 02:46:03

问题


I am trying to test the specifics of a rejected Promise, using Chai-as-Promised, Mocha, and the "should" dialect. Promises are implemented by bluebird.

This works fine:

it('it should be rejected when given bad credentials', function () {

   var promiseOfUsers = db.auth("bad", "credentials").getUsers();
   return promiseOfUsers.should.eventually.be.rejectedWith(Error)

});

There is a "status" property on that error. I would like to assert that status is 401

This does not work:

it('it should be rejected when given bad credentials', function () {

   var promiseOfUsers = db.auth("bad", "credentials").getUsers();
   return promiseOfUsers.should.eventually.be.rejectedWith(Error)
       .that.has.property('status')
       .that.equals(401)

});

It seems that any attempt to assert without referencing "rejected" or rejectedWith(Error), fails and just prints the error out to the console.

How can I delve into the reason for the rejection?


回答1:


I think rejectedWith() handler has some issues. But you can do like this:

promiseOfUsers.should.be.rejected.and.eventually.have.property("status",401)




回答2:


If you want to check if your promised was rejected and check the resulting object (aka the reason):

return fooPromise.should.be.rejected.and.eventually.deep.equal({
   'x': 1,
   'y': 1,
   'z': 2
})

You can change deep.equal to the any of the usual other chai matchers.

Note: This is an extension of @sertug's answer and hopefully will be useful for others coming here who looking for this.



来源:https://stackoverflow.com/questions/23985949/testing-for-specific-properties-of-rejected-promises-with-mocha-and-chai-as-pro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!