小编典典

我如何正确地用摩卡咖啡和柴测试诺言?

node.js

以下测试的行为异常:

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);
        })
});

我应该如何正确处理被拒绝的承诺(并进行测试)?

我应该如何正确处理失败的测试(即: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
    });
};

阅读 247

收藏
2020-07-07

共1个答案

小编典典

最简单的方法是使用Mocha在最新版本中提供的内置Promise支持:

it('Should return the exchange rates for btc_ltc', function() { // no done
    var pair = 'btc_ltc';
    // note the return
    return shapeshift.getRate(pair).then(function(data){
        expect(data.pair).to.equal(pair);
        expect(data.rate).to.have.length(400);
    });// no catch, it'll figure it out since the promise is rejected
});

或者使用现代Node和async / await:

it('Should return the exchange rates for btc_ltc', async () => { // no done
    const pair = 'btc_ltc';
    const data = await shapeshift.getRate(pair);
    expect(data.pair).to.equal(pair);
    expect(data.rate).to.have.length(400);
});

因为这种方法是端到端的承诺,所以它更易于测试,您不必考虑正在考虑的奇怪情况,就像done()到处都是奇怪的电话一样。

这是Mocha目前与Jasmine等其他库相比所具有的优势。您可能还需要检查Chai As
Promised
,这将使其变得更加容易(否.then),但就我个人而言,我更喜欢当前版本的清晰度和简洁性

2020-07-07