使用Mocha测试Promise链

14

我有如下形式的函数(使用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和assert):

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

所有这些都可以正常工作,但对于一个人来说感觉有些复杂。

我的主要问题是测试函数中 Promise 链的顺序。我尝试了几种方法(例如伪造一个具有 then 方法的对象,但无效;疯狂地模拟等),但似乎有些问题我没看到,在这方面我好像也没有获得关于 mocha 或 sinon 的文档信息。有人能提供一些指引吗?

谢谢。

计数

1个回答

7
摩卡支持 Promise,因此您可以这样做。
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");
}

在这种情况下,我该如何模拟someother1-6,以便不会调用实际的实现? - berlincount
如果catch中的断言失败,我会得到一个"可能未处理的AssertionError",如何让它正确地向上冒泡? - berlincount
@berlincount,你是否使用支持 Promise 的 Mocha 版本?如果是,请确保像答案中那样返回 Promise 链。 - Esailija
根据文档,使用Promise.onPossiblyUnhandledRejection(function(error){ throw error; });可以帮助解决问题。 - berlincount

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接