如何在Mocha测试用例中使用setTimeout()函数? [英] How can I use setTimeout() functions within Mocha test cases?
问题描述
我正在使用Mocha / Node js编写测试,并希望在执行代码块之前使用setTimeout等待一段时间。
I'm writing a test in Mocha / Node js and want to use a setTimeout to wait for a period before executing a block of code.
我该怎么办?完成这个?
How can I accomplish this?
看来在Mocha测试用例中,setTimeout()不起作用。 (我知道你可以为每个测试用例和每个测试文件设置setTimeout,这不是我在这里需要的。)
It appears that within a Mocha test case, setTimeout() does not work. (I am aware that you can setTimeout per test case and per test file, that's not what I need here.)
在运行Node的js文件中,即 node miniTest.js
,这将等待3秒,然后在setTimeout函数内打印行。
In a js file run with Node, ie, node miniTest.js
, this will wait 3 seconds, then print the line inside the setTimeout function.
console.log('waiting 3 seconds...');
setTimeout(function() {
console.log('waiting over.');
}, 3000);
在使用Mocha运行的js文件中,即 mocha smallTest.js
,这将不会等待,并且将完成执行并退出而不会在setTimeout函数中打印该行。
In a js file run with Mocha, ie, mocha smallTest.js
, this will not wait, and will finish executing and exit without ever printing the line inside the setTimeout function.
mocha = require('mocha');
describe('small test', function() {
it('tiny test case', function() {
console.log('waiting 3 seconds...');
setTimeout(function () {
console.log('waiting over.')
}, 3000);
});
});
推荐答案
您忘记在<$ c $中传递参数c> it('tiny test case',function()并在setTimeout方法中的console.log之后调用done()。
You are forgetting to pass parameter in it('tiny test case', function()
and call done() after console.log in setTimeout method.
describe('small test', function(){
it('tiny test case', function(done){
console.log('waiting 3 seconds');
setTimeout(function(){
console.log('waiting over.');
done();
}, 3000)
})
})
这篇关于如何在Mocha测试用例中使用setTimeout()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!