【问题标题】:Unit testing multiple asynchronous calls that return promises with Mocha使用 Mocha 对多个返回 Promise 的异步调用进行单元测试
【发布时间】:2016-09-21 21:13:03
【问题描述】:

我正在尝试了解如何最好地对我的异步 CommonJS 模块进行单元测试。在处理多个链式承诺时,我很难理解最佳实践。

假设我定义了以下模块:

module.exports = function(api, logger) {
    return api.get('/foo')
        .then(res => {
            return api.post('/bar/' + res.id)
        })
        .then(res => {
            logger.log(res)
        })
        .catch(err => {
            logger.error(err)
        })
}

我有以下规范文件试图测试是否进行了正确的调用。

var module = require('./module')
describe('module()', function() {
    var api;
    var logger;
    var getStub;
    var postStub;
    beforeEach(function() {
        getStub = sinon.stub();
        postStub = sinon.stub();
        api = {
            get: getStub.resolves({id: '123'),
            post: postStub.resolves()
        }
        logger = {
            log: sinon.spy(),
            error: sinon.spy()
        }
    })
    afterEach(function() {
        getStub.restore();
        postStub.restore();
    });
    it('should call get and post', function(done) {
        module(api, logger) // System under test
        expect(getStub).to.have.been.calledWith('/foo')
        expect(postStub).to.have.been.calledWith('/bar/123')
        done()
    })
})

这不起作用。第一个断言正确通过,但第二个断言失败,因为可能在执行时承诺尚未解决。

我可以使用 process.nextTick 或 setTimeout 解决此问题,但我想看看其他人如何更优雅地解决此问题。

我尝试将 chai-as-promised 添加到组合中,但运气不佳。我当前的设置包括 sinon、chai、sinon-as-promised 和 sinon-chai。

谢谢

【问题讨论】:

    标签: javascript node.js mocha.js sinon chai


    【解决方案1】:

    您应该使用 module() 返回一个承诺这一事实,因此您可以将另一个 .then() 添加到可以断言参数的链中(因为此时已经调用了前面的 .then() 步骤,包括致电api.post())。

    而且由于 Mocha 支持 Promise,您可以返回结果 Promise,而不必处理 done

    it('should call get and post', function() {
      return module(api, logger).then(() => {
        expect(getStub).to.have.been.calledWith('/foo')
        expect(postStub).to.have.been.calledWith('/bar/123')
      });
    })
    

    【讨论】:

    • 谢谢。现在看起来非常简单。我错过了导致处理 done() 的各种问题的返回
    猜你喜欢
    • 2016-02-21
    • 2019-05-24
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    • 2014-03-19
    • 1970-01-01
    相关资源
    最近更新 更多