相关疑难解决方法(0)

如何用mocha和chai正确测试承诺?

以下测试表现得很奇怪:

it('Should return the exchange rates for btc_ltc', function(done) {
    var pair = 'btc_ltc';

    shapeshift.getRate(pair)
        .then(function(data){
            expect(data.pair).to.equal(pair);
            expect(data.rate).to.have.length(400);
            done();
        })
        .catch(function(err){
            //this should really be `.catch` for a failed request, but
            //instead it looks like chai is picking this up when a test fails
            done(err);
        })
});
Run Code Online (Sandbox Code Playgroud)

我该如何妥善处理被拒绝的承诺(并对其进行测试)?

我该如何正确处理失败的测试(即:expect(data.rate).to.have.length(400);

这是我正在测试的实现:

var requestp = require('request-promise');
var shapeshift = module.exports = {};
var url = 'http://shapeshift.io';

shapeshift.getRate = function(pair){
    return requestp({
        url: url + '/rate/' + pair,
        json: true
    }); …
Run Code Online (Sandbox Code Playgroud)

mocha.js node.js promise chai

140
推荐指数
3
解决办法
8万
查看次数

测试在Mocha/Chai中拒绝了承诺

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

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;
  });
};
Run Code Online (Sandbox Code Playgroud)

在我的测试中:

return expect(s.sendNote(data)).to.eventually.be.rejectedWith('Boo');
Run Code Online (Sandbox Code Playgroud)

但是,当测试通过时,它会将错误抛出到控制台.

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

对于非promise错误,我使用bind来测试以防止在Chai可以包装和测试之前抛出错误:

return expect(s.sendNote.bind(s, data)).to.eventually.be.rejectedWith('Boo'); …
Run Code Online (Sandbox Code Playgroud)

javascript mocha.js promise bluebird chai-as-promised

13
推荐指数
3
解决办法
2万
查看次数