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

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

本文介绍了我如何正确地用摩卡咖啡和柴测试诺言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下测试的行为很奇怪:

The following test is behaving oddly:

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

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

How should I properly handle a rejected promise (and test it)?

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

How should I properly handle a failed test (ie: expect(data.rate).to.have.length(400);?

这是我正在测试的实现:

Here is the implementation I'm testing:

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

推荐答案

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

The easiest thing to do would be to use the built in promises support Mocha has in recent versions:

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:

Or with modern Node and 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()调用.

Since this approach is promises end to end it is easier to test and you won't have to think about the strange cases you're thinking about like the odd done() calls everywhere.

这是Mocha目前与Jasmine等其他库相比所具有的优势.您可能还需要检查承诺的柴,这样做会更加容易( .then),但就我个人而言,我更喜欢当前版本的清晰度和简洁性

This is an advantage Mocha has over other libraries like Jasmine at the moment. You might also want to check Chai As Promised which would make it even easier (no .then) but personally I prefer the clarity and simplicity of the current version

这篇关于我如何正确地用摩卡咖啡和柴测试诺言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:03