单元测试多个异步调用,这些调用使用Mocha返回承诺

nic*_*eli 5 javascript mocha.js node.js sinon chai

我试图了解如何最好地对异步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)
        })
}
Run Code Online (Sandbox Code Playgroud)

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

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()
    })
})
Run Code Online (Sandbox Code Playgroud)

这行不通。第一个断言正确传递,但是第二个断言失败,因为可能在执行时未解决承诺。

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

我试过在运气不好的情况下将蔡依如许加入其中。我当前的设置包括sinon,chai,promised和sinon-chai。

谢谢

rob*_*lep 1

module()您应该使用返回 Promise 的事实,这样您就可以将另一个 Promise 添加.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')
  });
})
Run Code Online (Sandbox Code Playgroud)