小编nic*_*eli的帖子

单元测试多个异步调用,这些调用使用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)
        })
}
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', …
Run Code Online (Sandbox Code Playgroud)

javascript mocha.js node.js sinon chai

5
推荐指数
1
解决办法
1663
查看次数

标签 统计

chai ×1

javascript ×1

mocha.js ×1

node.js ×1

sinon ×1