测试在Mocha / Chai中拒绝了承诺 [英] Testing rejected promise in Mocha/Chai

查看:126
本文介绍了测试在Mocha / Chai中拒绝了承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个拒绝承诺的课程:

I have a class that rejects a promise:

Sync.prototype.doCall = function(verb, method, data) {
  var self = this;

  self.client = P.promisifyAll(new Client());

  var res = this.queue.then(function() {
    return self.client.callAsync(verb, method, data)
      .then(function(res) {
        return;
      })
      .catch(function(err) {    
        // This is what gets called in my test    
        return P.reject('Boo');
      });
  });

  this.queue = res.delay(this.options.throttle * 1000);
  return res;
};

Sync.prototype.sendNote = function(data) {
  var self = this;
  return self.doCall('POST', '/Invoice', {
    Invoice: data
  }).then(function(res) {
    return data;
  });
};

在我的测试中:

return expect(s.sendNote(data)).to.eventually.be.rejectedWith('Boo');

然而,当测试通过时,它会将错误抛给控制台。

However while the test passes it throws the error to the console.

未处理的拒绝错误:Boo
...

Unhandled rejection Error: Boo ...

对于非承诺错误,我使用了bind来测试以防止错误抛出直到Chai可以换行并测试:

With non promise errors I have used bind to test to prevent the error from being thrown until Chai could wrap and test:

return expect(s.sendNote.bind(s, data)).to.eventually.be.rejectedWith('Boo');

但是这不适用于此并返回:

However this does not work with this and returns:

TypeError: [功能]不是一个可以。

TypeError: [Function] is not a thenable.

测试的正确方法是什么这个?

What is the correct way to test for this?

推荐答案

您收到错误是因为sendNote被拒绝而且您没有抓住它。

You're getting the error because sendNote is being rejected and you're not catching it.

尝试:

var callPromise = self.doCall('POST', '/Invoice', {
  Invoice: data
}).then(function(res) {
  return data;
});

callPromise.catch(function(reason) {
  console.info('sendNote failed with reason:', reason);
});

return callPromise;

看起来您还必须将现有的一个区块移出:

Looks like you'll also have to move your existing catch one block out:

var res = this.queue.then(function() {
  return self.client.callAsync(verb, method, data)
    .then(function(res) {
      return;
    });
  }).catch(function(err) {    
    // This is what gets called in my test    
    return P.reject('Boo');
  });

这篇关于测试在Mocha / Chai中拒绝了承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆