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

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

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

我怎样才能做到这一点?

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

在带有 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);
    });
});

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

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

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

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

您需要在测试中完成作为参数传递,测试通过后将调用该参数。

你可以这样写你的测试

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() 。您可以省略 before 函数并在您的 it 函数之一中执行 setTimeout,但它仍应在断言后使用并调用 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();
  });

});