Mocha,应该——当测试包含promise的异步函数时,断言错误是沉默的

Mocha, should - when testing async function that has promise in it, assertion errors are silent

本文关键字:断言 沉默 函数 错误 promise 应该 测试 包含 Mocha 异步      更新时间:2023-09-26

我有一个小问题困扰我…下面的代码显示了一个异步测试,在这个测试中,我们测试了一个我们无法控制的代码(测试的黑盒子,我可以改变它)。

黑盒代码在完成后分派事件,测试监听该事件并断言数据。

问题是当有一个断言错误时,异常被抛出并被promise错误处理程序捕获,而不是由测试框架捕获,因此done函数永远不会执行,并且我们得到超时错误。

很容易通过尝试&catch在it()块中,但是总是使用try &Catch在it()块内?到目前为止,我信任测试框架来处理异常

另一个问题是,错误是沉默的,除非catch输出它,因为它是黑盒子,我们不能指望它。

这里的技巧帮助我解决了这个问题,但我不喜欢解决方案:https://github.com/mochajs/mocha/issues/1128 issuecomment - 40866763

它与其他类似的问题不同,因为在it()块中我们没有任何对promise对象的引用。

describe.only("test", function () {
  var event;
  // blackbox simulates a code we have no controler over
  // inside this code we have a promise, when this promise resolves it triggers event
  var blackbox = function () {
    var promise = new Promise(function (resolve, reject) {
      resolve();
    });
    promise.then(function () {
      event(4);
    }).catch(function (e) {
      console.log(e);
    });
  };
  it("async with blackbox promise", function (done) {
    // this simulates event listenner, when the event is triggered the code executes
    event = function (data) {
      // this assertion works and everything is fine
      data.should.be.equal(4);
      // this assertion thrown exception that is being cought by the promise reject handler and
      // isnt cought by the testing framework (chai / mocha)
      data.should.be.equal(5);
      // because the exception is thrown we never reach the done
      done();
    };
    blackbox();
  });
});

mocha中测试承诺的方式是返回它们并让它决定何时失败或不失败。

因此,第一步是使承诺在blackbox函数中可用:

// blackbox simulates a code we have no controler over
// inside this code we have a promise, when this promise resolves it triggers event
var blackbox = function () {
  var promise = new Promise(function (resolve, reject) {
    resolve();
  });
  return promise.then(function () {
    event(4);
  });
  // do not catch here unless you want the test to not fail on error
};

现在让我们修改测试代码来处理承诺:

it("async with blackbox promise", function () {
  // this simulates event listenner, when the event is triggered the code executes
  event = function (data) {
    // this assertion works and everything is fine
    data.should.be.equal(4);
    // this assertion thrown exception that is being cought by the promise reject handler
    data.should.be.equal(5);
  };
  // mocha will append a rejection handler to this promise here and fail if it gets called
  return blackbox();
});