为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

拉莫斯之舞 2019-09-20 16:48:26
以下测试表现得很奇怪: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    });};
查看完整描述

3 回答

?
青春有我

TA贡献1784条经验 获得超8个赞

这是我的看法:

运用 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子句返回测试。如果你不想测试其他任何东西,请使用另一个() - 阻止。


查看完整回答
反对 回复 2019-09-20
  • 3 回答
  • 0 关注
  • 762 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信