繁体   English   中英

单元测试使用Mocha返回promise的多个异步调用

[英]Unit testing multiple asynchronous calls that return promises with Mocha

我试图了解如何最好地单元测试我的异步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解决这个问题,但我想看看其他人如何更优雅地解决这个问题。

我已经尝试过将运气添加到混合物中而运气不佳。 我现在的设置包括,sinon,chai,sinon-as-promise和sinon-chai。

谢谢

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

由于Mocha支持承诺,您可以返回由此产生的承诺,而不必处理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')
  });
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM