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

问题描述:

我有一个功能,通过回调像函数(错误,结果){...}作为参数来解决。我试图使用摩卡来测试这个函数,但问题是函数返回异步,所以没有好的地方让我把done()。如果我将其放入结果处理程序中,则需要太长的时间和摩卡超时。如果我把它放在外面,测试总是通过,因为处理程序还没有被调用。这是我的代码。解决这个问题的最好方法是什么?在节点中,你如何等待回调被调用?

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

'lbl.createLabels'需要多长时间?如果超过2秒,摩卡将超时_使用其默认超时值_。如果您知道该通话可能需要5秒钟,则可以增加超时限制。见[this](https://mochajs.org/#timeouts)。在任何情况下,对'done'的调用应该在回调到'lbl.createLabels'的内部。 – robertklep

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

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

测试与摩卡异步代码不能简单!只需在测试完成时调用回调。通过向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(); 
      }); 
     }); 
    }); 
}); 
+0

我认为OP的观点是这两个地方的回调可以在他们的代码中导致测试结果不起作用,不是吗? –

+0

@DaveNewton是啊! – user3685285