我如何在Mocha测试用例中使用setTimeout()函数

How can I use setTimeout() functions within Mocha test cases?

本文关键字:setTimeout 函数 Mocha 测试用例      更新时间:2023-09-26

我正在Mocha/Node js中编写一个测试,并希望在执行代码块之前使用setTimeout等待一段时间。

我怎样才能做到这一点?

似乎在Mocha测试用例中,setTimeout()不起作用。(我知道您可以为每个测试用例和每个测试文件设置timeout,这不是我在这里需要的。)

在使用Node运行的js文件中,例如node miniTest.js,这将等待3秒,然后在setTimeout函数中打印该行。

miniTest.js

console.log('waiting 3 seconds...');
setTimeout(function() {
    console.log('waiting over.');
}, 3000);

在使用Mocha运行的js文件中,例如mocha smallTest.js,这将不会等待,并且将完成执行并退出,而不会在setTimeout函数中打印行。

smallTest.js:

mocha = require('mocha');
describe('small test', function() {
    it('tiny test case', function() {
        console.log('waiting 3 seconds...');
        setTimeout(function () {
            console.log('waiting over.')
        }, 3000);
    });
});

您忘记在it('tiny test case', function()中传递参数并在console.log中调用setTimeout方法后调用done()

describe('small test', function(){
   it('tiny test case', function(done){
       console.log('waiting 3 seconds');
       setTimeout(function(){
           console.log('waiting over.');
           done();
       }, 3000)
   })
})

您需要在测试中将done passed作为一个参数,该参数将在测试通过后被调用。

你可以像

那样写你的测试
mocha = require('mocha');
describe('small test', function(done) {
    it('tiny test case', function() {
       console.log('waiting 3 seconds...');
       setTimeout(function () {
           console.log('waiting over.');
           done();
       }, 3000);
    });

});

这将等待3秒,之后它将打印'waiting over'并通过测试。您还可以在超时内设置一个条件,这取决于该条件是否满足。您可以通过调用

来通过测试。
done();

或通过抛出错误或在

中传递错误消息而使测试失败
done("Test Failed");

让您的测试函数接受一个参数(通常称为done)。Mocha将传递一个函数,您将在setTimeout函数中调用该函数(例如,在console.log调用done()之后)。

看到https://mochajs.org/异步代码。

这是一个完整的示例。您需要在每个断言中调用done()。你可以省略before函数,在其中一个it函数中执行setTimeout,但它仍然应该在assert之后使用并调用done()。

var foo = 1;
before(function(done) {
  setTimeout(function(){
    foo = 2;
    done();
  }, 500)
});
describe("Async setup", function(done){
  it("should have foo equal to 2.", function(done){
    expect(foo).to.be.equal(2);
    done();
  });
  it("should have foo not equal 3.", function(done){
    expect(foo).to.be.not.equal(3);
    done();
  });
});