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

时间:2014-08-27 22:13:55

标签: javascript node.js mocha

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

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

6 个答案:

答案 0 :(得分:17)

setTimeout肯定会有所帮助,但可能有一种“更清洁”的方式来做到这一点。 docs actually says在测试异步代码时使用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);
 });

答案 1 :(得分:9)

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

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

答案 2 :(得分:1)

首先,对于正确的单元测试,您在测试之间永远不需要睡眠。如果确实需要睡眠,则意味着要测试的功能需要延迟才能完成其预期的任务,该任务必须在该函数内部进行处理,并需要进行一些异步等待或睡眠。从函数退出后,其生存期必须结束并且必须立即获得预期结果。

答案 3 :(得分:1)

第一

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

附带说明:您还可以一个接一个地使用延迟功能,并且仍然保持一致性(测试顺序)

答案 4 :(得分:1)

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

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

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

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

答案 5 :(得分:0)

这是另一个,使用诺言:

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);
相关问题