如何在Mocha中处理异步测试?

时间:2018-03-07 10:17:32

标签: node.js mocha-phantomjs

我有一个事件处理函数,它将一些事件数据和一个回调函数作为输入。

此事件处理程序正在使用promise来完成其工作:

function myHandler(event, callback) {
  somePromise(event).then((result) => {
    if (result.Error) {
      callback(error);
    } else {
      callback(null, result.SuccessData);
    }
  });
}

我有以下代码来测试处理程序:

it('test handler', function(done) {
  let event = {...};
  myHandler(event, function(error, success) {
    expect(success).to.not.be.null;
    expect(error).to.be.null;
    expect(success.member).to.be.equal('expected');
    done();
  }
});

运行此测试时,我收到此错误:

(node:3508) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): AssertionError: expected 'unexpected' to equal 'expected'

并且所有测试结束:

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

但是测试仍在通过......

为什么在调用done()函数时会出现此错误?

2 个答案:

答案 0 :(得分:2)

将测试包含在承诺中,如果断言失败,则拒绝承诺。

it('test handler', () => {
  let event = {...}
  return new Promise((resolve, reject) => {
    myHandler(event, (error, success) => {
      try {
        expect(success).to.not.be.null;
        expect(error).to.be.null;
        expect(success.member).to.be.equal('expected');
        resolve();
      } catch (err) {
        reject(err);
      }
    });
  });
});

答案 1 :(得分:1)

您正在使用Promises。 您可以在不使用done的情况下返回您的承诺,如下所示:

// Note the absence of the done callback here
it('test handler', function() {
  let event = {...};
  return myHandler(event, function(error, success) {
    expect(success).to.not.be.null;
    expect(error).to.be.null;
    expect(success.member).to.be.equal('expected');
  }
});

或使用Chai As Promised

it('test handler', function(done) {
  let event = {...};
  myHandler(event, function(error, success) {
    expect(success).to.not.be.null;
    expect(error).to.be.null;
    expect(success.member).to.be.equal('expected');
  }.should.notify(done)
});

后者对我来说似乎更好,就好像你忘记了第一个例子中的return一样,你的测试可能会无声地失败。

相关问题