【问题标题】:Testing Promise-chains with Mocha用 Mocha 测试 Promise 链
【发布时间】:2015-02-17 00:15:52
【问题描述】:

我有以下风格的函数(在 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();
            });
        });
});

所有这些都可以正常工作,但感觉很复杂。

我的主要问题是在函数中测试 Promises 链(和顺序)。我已经尝试了几件事(用 then 方法伪造一个对象,这不起作用;像疯了一样嘲笑它等);但似乎有些东西我没有看到,而且我似乎没有得到这方面的 mocha- 或 sinon- 文档。

有人指点吗?

谢谢

计数

【问题讨论】:

    标签: javascript node.js unit-testing mocha.js bluebird


    【解决方案1】:

    Mocha 支持 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,因此不会调用实际的实现?
    • 嗯。如果 catch 中的断言失败,我得到一个“可能未处理的 AssertionError”,我怎样才能让它正确冒泡?
    • @berlincount 您使用的是支持承诺的 mocha 版本吗?如果是,你确定你是returning 承诺链,就像答案中一样
    • 我是。使用 Promise.onPossiblyUnhandledRejection(function(error){ throw error; });根据文档帮助。
    猜你喜欢
    • 2017-04-08
    • 2016-11-20
    • 2015-07-16
    • 2015-12-01
    • 2017-02-04
    • 2013-02-10
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    相关资源
    最近更新 更多