简体   繁体   English

使用Mocha和Chai-as-Promised测试被拒绝承诺的特定属性

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

I am trying to test the specifics of a rejected Promise, using Chai-as-Promised , Mocha , and the "should" dialect. 我试图用Chai-as-PromisedMocha和“should”方言来测试被拒绝的Promise的细节。 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. 该错误有一个“status”属性。 I would like to assert that status is 401 我想声称状态是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? 我该如何深入研究拒绝的原因?

I think rejectedWith() handler has some issues. 我认为rejectedWith()处理程序有一些问题。 But you can do like this: 但你可以这样做:

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

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 . 您可以将deep.equal更改为任何其他常见的chai matchers

Note: This is an extension of @sertug's answer and hopefully will be useful for others coming here who looking for this. 注意:这是@ sertug答案的延伸,希望对于那些正在寻找此问题的人来说非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM