如何使用 mocha 和 chai 正确测试 promise? [英] How do I properly test promises with mocha and chai?

查看:59
本文介绍了如何使用 mocha 和 chai 正确测试 promise?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下测试表现异常:

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

由于这种方法是端到端的 promise,因此更易于测试,并且您不必考虑您正在考虑的奇怪情况,例如到处都是奇怪的 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)的优势.您可能还想查看 Chai As Promised 这将使它更容易(没有.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

这篇关于如何使用 mocha 和 chai 正确测试 promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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