在节点中,您如何等待调用回调?

时间:2017-04-08 05:49:17

标签: node.js asynchronous mocha chai

我有一个函数可以通过将函数(错误,结果){...}作为参数进行回调来解析。我试图使用mocha来测试这个函数,但问题是函数异步返回,因此我没有放置done()的好地方。如果我放入我的结果处理程序,它需要太长时间并且mocha超时。如果我把它放在外面,测试总是通过,因为处理程序还没有被调用。这是我的代码。什么是最好的解决方法?

lbl.createLabels是一个函数,它接受一组客户和一个目录,并在该目录中创建一堆文件,然后异步调用类型为:function(error,callback)的回调。

describe('Tests', () => {
    it('returns a list of customer objects', (done) => {
        lbl.createLabels(customers, __dirname + "/..", (err, result) => {
            err.should.equal(undefined)
            result.should.be.a('array')
            result[0].should.have.property('id')
            result[0].should.have.property('tracking')
            result[0].should.have.property('pdfPath')
            const a = {prop:3}
            a.prop.should.be.an('array')
            done() // putting done() here results in a timeout
        })
        done() // putting done here results in the test exiting before the callback gets called
    })
})

1 个答案:

答案 0 :(得分:1)

Mocha的文档有一整节描述了如何测试异步代码:

https://mochajs.org/#asynchronous-code

  

使用Mocha测试异步代码并不简单!只需在测试完成后调用回调。通过向done添加回调(通常名为it()),Mocha将知道它应该等待调用此函数来完成测试。

describe('User', function() {
    describe('#save()', function() {
        it('should save without error', function(done) {
            var user = new User('Luna');
            user.save(function(err) {
                if (err) done(err);
                else done();
            });
        });
    });
});
相关问题