让Mocha在运行下一个测试之前等待

R.A*_*cas 14 javascript mocha.js node.js

有一些mocha测试需要先前函数调用的数据,但之后因为它使用了web服务,并且希望它在运行下一个测试之前确实等待预定的时间,例如:

var global;

it('should give some info', function(done) {
  run.someMethod(param, function(err, result) {
    global = result.global
  done();
  });
});

wait(30000); // basically block it from running the next assertion

it('should give more info', function(done) {
  run.anotherMethod(global, function(err, result) {
    expect(result).to.be.an('object');
  done();
  });
});
Run Code Online (Sandbox Code Playgroud)

任何想法,将不胜感激.谢谢!

Flo*_*ops 20

setTimeout绝对可以提供帮助,但可能有一种"更清洁"的方式来做到这一点. 文档实际上说的使用setTimeout,以避免超时错误而测试异步代码,所以要小心.

var global;

it('should give some info', function(done) {
  run.someMethod(param, function(err, result) {
    global = result.global
  done();
  });
});

it('should give more info', function(done) {
    this.timeout(30000);

    setTimeout(function () {
      run.anotherMethod(global, function(err, result) {
        expect(result).to.be.an('object');
        done();
      });
    }, 30000);
 });
Run Code Online (Sandbox Code Playgroud)


Dav*_*ral 14

就我而言,我正在编写RESTful API一个NodeJS本地操作一些文件的代码。当我启动测试时,API 正在接收多个请求,这使得我的 API 同时操作机器中的这些文件,这给我带来了一个问题。

因此,我需要1 sec在这些 API 调用之间留出一些时间(就足够了)。对我来说,解决方案如下:

beforeEach( async () => {
   await new Promise(resolve => setTimeout(resolve, 1000));
   console.log("----------------------");
});
Run Code Online (Sandbox Code Playgroud)

现在,在每次it()测试之前,都会运行前一个函数,并且在 API 调用之间我有 1 秒的睡眠时间。

  • 完美的!IMO 这应该是公认的答案。 (4认同)

Zla*_*tko 10

虽然this.timeout()会延长单个测试的超时时间,但它不是您问题的答案.this.timeout()设置当前测试的超时.

但不要担心,无论如何你应该没事.测试并非并行运行,它们是串行完成的,因此您的全局方法不应该有问题.


ymz*_*ymz 5

第一的:

这个线程有很好的答案!我个人喜欢@Flops 的回答(得到了我的赞成)

第二:

为了澄清这一点(尽可能多地),这里有一个代码示例,与我最终得到的代码示例非常相似(经过测试和验证)

function delay(interval) 
{
   return it('should delay', done => 
   {
      setTimeout(() => done(), interval)

   }).timeout(interval + 100) // The extra 100ms should guarantee the test will not fail due to exceeded timeout
}

it('should give some info', function(done) {
  run.someMethod(param, function(err, result) {
    global = result.global
  done();
  });
});

delay(1000)

it('should give more info', function(done) {
  run.anotherMethod(global, function(err, result) {
    expect(result).to.be.an('object');
  done();
  });
});
Run Code Online (Sandbox Code Playgroud)

旁注:您也可以一个接一个地使用延迟函数,并且仍然保持一致性(测试顺序)