当`should`期望失败时使用带有mocha和chai的promises时出现超时错误

时间:2017-07-18 15:24:19

标签: promise mocha chai

用Mocha& amp;编写项目测试时Chai我注意到我可能会让true.should.be.false失败,但当被测变量来自一个承诺并且期望失败时,Mocha会超时:Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

以下是我尝试过的事情(以及解决方案)的示例,希望它能在未来为某人提供帮助。

const chai = require('chai');
const should = chai.should();
const assert = chai.assert;

function getFoo() {
  return new Promise((resolve, reject) => {
    resolve({bar: true});
  });
}

describe('Example for StackOverflow', function() {

  it('will fail as expected', function() {
    true.should.be.false;
  });

  it('will also fail as expected', function() {
    var foo = {
      bar: true
    };

    foo.bar.should.be.false;
  });

  it('times out instead of fails', function(done) {
    getFoo().then(data => {
      data.bar.should.be.false;
      done();
    });
  });

  it('times out instead of fails even without arrow notation', function(done) {
    getFoo().then(function(data) {
      data.bar.should.be.false;
      done();
    });
  });

  it('should throws an error when the expectation fails, but the done() in catch() doesnt seem to matter', function(done) {
    getFoo().then(data => {
      data.bar.should.be.false;
      done();
    })
    .catch(error => {
      console.error(error);
      done();
    })
    .catch(error => {
      console.error(error);
      done();
    });
  });

  it('still throws an error in the catch() if I try to use assert.fail() inside the catch to force a failure', function(done) {
    getFoo().then(data => {
      data.bar.should.be.false;
      done();
    })
    .catch(error => {
      console.error(error);
      assert.fail(0, 1);
      done();
    })
    .catch(error => {
      console.error(error);
      done();
    });
  });

});

供参考,以下是这里的版本:

  • node:v5.12.0
  • chai:v4.1.0
  • mocha:v3.4.2

这与node.js how to get better error messages for async tests using mocha的不同之处在于,我特别谈到should检测到失败时发生的超时,并抛出一个未被捕获的错误,因为承诺不归还。他们的解决方案侧重于使用done - 我不需要它,因为它将承诺返回给Mocha,以便它可以捕获错误。

1 个答案:

答案 0 :(得分:0)

解决方法是在测试函数中返回承诺 - 我没有在我的times out instead of fails示例中执行此操作,后来我在编写示例时注意到了问这个问题。

const chai = require('chai');
const should = chai.should();
const assert = chai.assert;

function getFoo() {
  return new Promise((resolve, reject) => {
    resolve({bar: true});
  });
}

describe('Example for StackOverflow', function() {

  it('needs to return the promise for the test runner to fail the test on a thrown exception - no done necessary', function() {
    return getFoo().then(data => {
      data.bar.should.be.false;
    });
  });

});