繁体   English   中英

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

[英]Make Mocha wait before running next test

我有一些 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();
  });
});

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

setTimeout肯定会有所帮助,但可能有一种“更干净”的方法来做到这一点。

这里的文档实际上说在测试异步代码时使用this.timeout(delay)来避免超时错误,所以要小心。

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);
 });

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

不过别担心,反正你应该没事的。 测试不是并行运行的,它们是串行进行的,因此您的全局方法应该没有问题。

第一的:

这个线程有很好的答案! 我个人喜欢@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();
  });
});

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

就我而言,我在NodeJS中编写了一个RESTful API ,用于在本地操作一些文件。 当我开始测试时,API 收到了多个请求,它让我的 API 同时操作机器中的这些文件,这导致了我的问题。

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

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

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

首先,为了正确的单元测试,你不应该在测试之间需要一些睡眠。 如果您确实需要睡眠,这意味着您正在测试的函数在完成其预期任务之前需要延迟,这些任务必须在该函数内部处理,并带有一些异步等待或睡眠。 在退出函数时,它的生命周期必须结束,并且必须立即获得预期的结果。

这是另一个,使用承诺:

it('go, then stop', (done) => {
// this.skip();
go()
  .then((response) => { console.log('go was called'); return response; })
  .then(response => response.should.equal('acknowledged'))
  .then(() => new Promise(resolve => setTimeout(() => { resolve(); }, 3000)))
  .then(() => console.log('3 second wait is over'))
  .then(() => stop())
  .then(response => response.should.equal('acknowledged'))
  .then(() => done());
  }).timeout(15000);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM