簡體   English   中英

使用Mocha測試Promise-chains

[英]Testing Promise-chains with Mocha

我有以下樣式的函數(在Node.JS下使用bluebird promises):

module.exports = {
    somefunc: Promise.method(function somefunc(v) {
        if (v.data === undefined)
            throw new Error("Expecting data");

        v.process_data = "xxx";

        return module.exports.someother1(v)
          .then(module.exports.someother2)
          .then(module.exports.someother3)
          .then(module.exports.someother4)
          .then(module.exports.someother5)
          .then(module.exports.someother6);
    }),
});

我正在嘗試測試(使用mocha,sinon,斷言):

// our test subject
something = require('../lib/something');

describe('lib: something', function() {
    describe('somefunc', function() {
        it("should return a Error when called without data", function(done) {
            goterror = false;
            otherexception = false;
            something.somefunc({})
            .catch(function(expectedexception) {
                try {
                    assert.equal(expectedexception.message, 'Expecting data');
                } catch (unexpectedexception) {
                    otherexception = unexpectedexception;
                }
                goterror = true;
            })
            .finally(function(){
                if (otherexception)
                    throw otherexception;

                 assert(goterror);
                 done();
            });
        });
});

所有這些都是這樣的,但對於一個人來說卻感到錯綜復雜。

我的主要問題是測試函數中的Promises-chain(和order)。 我嘗試了幾件事(用一種方法偽造一個物體,這種方法不起作用;嘲笑它就像瘋了一樣); 但似乎有一些我沒有看到的東西,而且我似乎沒有得到這方面的摩卡或頌歌文件。

有人有指點嗎?

謝謝

計數

Mocha支持承諾,所以你可以做到這一點

describe('lib: something', function() {
    describe('somefunc', function() {
        it("should return a Error when called without data", function() {
            return something.somefunc({})
                .then(assert.fail)
                .catch(function(e) {
                    assert.equal(e.message, "Expecting data");
                });
        });
    });
});

這大致相當於同步代碼:

try {
   something.somefunc({});
   assert.fail();
} catch (e) {
   assert.equal(e.message, "Expecting data");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM