【问题标题】:In node, how do you wait until a callback has been called?在节点中,你如何等到回调被调用?
【发布时间】:2017-09-03 13:53:45
【问题描述】:

我有一个函数,它通过像 function(error, result) { ... } 这样的回调作为参数来解决。我正在尝试使用 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
    })
})

【问题讨论】:

  • lbl.createLabels 需要多长时间?如果超过 2 秒,Mocha 将使用其默认超时值超时。如果您知道该调用可能需要 5 秒,您可以增加超时限制。见this。在任何情况下,对done 的调用都应该在对lbl.createLabels 的回调中进行。

标签: node.js asynchronous mocha.js chai


【解决方案1】:

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

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

使用 Mocha 测试异步代码再简单不过了!只需在测试完成时调用回调。通过向it() 添加回调(通常命名为done),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();
            });
        });
    });
});

【讨论】:

  • 我认为 OP 提出的观点是回调可能进入其代码的两个位置导致测试无法正常工作,不是吗?
  • @DaveNewton 是的!
猜你喜欢
  • 2019-05-22
  • 2018-09-14
  • 2020-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-06
  • 1970-01-01
相关资源
最近更新 更多