【发布时间】: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