如何用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);

        })

});

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


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

    });

};


拉莫斯之舞
浏览 758回答 3
3回答

青春有我

这是我的看法:运用 async/await不需要额外的柴模块避免捕获问题,@ TheCrazyProgrammer在上面指出延迟的promise函数,如果延迟为0则失败:const timeoutPromise = (time) => {    return new Promise((resolve, reject) => {        if (time === 0)            reject({ 'message': 'invalid time 0' })        setTimeout(() => resolve('done', time))    })}//                     ↓ ↓ ↓it('promise selftest', async () => {    // positive test    let r = await timeoutPromise(500)    assert.equal(r, 'done')    // negative test    try {        await timeoutPromise(0)        // a failing assert here is a bad idea, since it would lead into the catch clause…    } catch (err) {        // optional, check for specific error (or error.type, error. message to contain …)        assert.deepEqual(err, { 'message': 'invalid time 0' })        return  // this is important    }    assert.isOk(false, 'timeOut must throw')    log('last')})积极的测试相当简单。意外故障(模拟500→0)会自动失败,因为被拒绝的承诺会升级。否定测试使用try-catch-idea。但是:'抱怨'不希望的传递只发生在catch子句之后(这样,它不会在catch()子句中结束,触发进一步但误导性的错误。要使此策略起作用,必须从catch子句返回测试。如果你不想测试其他任何东西,请使用另一个() - 阻止。
打开App,查看更多内容
随时随地看视频慕课网APP