mocha と chai を使って Promise を適切にテストするにはどうすればよいですか? 質問する

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

拒否された Promise を適切に処理 (およびテスト) するにはどうすればよいでしょうか?

失敗したテストを適切に処理するにはどうすればよいですか (例: 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
    });
};

ベストアンサー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()このアプローチはエンドツーエンドの Promise であるため、テストが容易になり、あらゆる場所での奇妙な呼び出しなど、考えていた奇妙なケースについて考える必要がなくなります。

これは現時点でMochaがJasmineのような他のライブラリよりも優れている点です。約束通りのチャイそれはさらに簡単になります(いいえ.then)が、個人的には現在のバージョンの明快さとシンプルさを好みます

おすすめ記事