正确地调用mocha完成回调和承诺

时间:2016-06-20 10:17:26

标签: javascript mocha

我的应用中有几个集成测试:

 it('creating vehicle', function (done) {
    createVehicle()         
      .then(() => {
        done();
      })
      .catch((err) => {
        done(err);
      });
  });

createVehicle发布请求并返回承诺:

 return request.json('post', '/api/vehicle/')
    .send(obj)
    .expect(200)
    .then((res) => {
      expect(res.body).toExist("Body is empty");
      expect(res.body.id).toExist("Id is empty");     
      return res.body;
    });

现在一切正常,但如果我按以下方式重写第一个片段:

it('creating vehicle', function (done) {
        createVehicle()         
          .then(done) //*
          .catch(done); //*
      });

我从Mocha那里得到错误

  

使用非错误

调用done()

我理解为什么。 createVehicle返回res.body并将其传递给then回调,结果done运行为done(arg),我收到错误,因为mocha {当没有错误时,必须在没有arg的情况下调用{1}}回调,并在出现错误时调用参数。

是否可以使用此变体:

done

如何实现这一目标?

当然,我可以删除return语句,但 .then(done) .catch(done); 在几个地方使用,我需要返回值:

createVehicle

1 个答案:

答案 0 :(得分:1)

最简单的解决方案是返回承诺而不必处理回调,因为Mocha supports promises out-of-the-box

it('creating vehicle', function() {
  return createVehicle();
});
相关问题