使用 Mocha 测试 Promise

Testing Promises with Mocha

我一直在尝试使用 Mocha 测试以下代码,但我总是遇到错误。

Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test

我要测试的代码如下

'use strict'
const Promise = require('bluebird');

const successResponse = {status: 'OK'};
const failResponse = {status: 'FAIL'};

function dbStatusSuccess () {
    return new Promise(function(resolve, reject) {
        setTimeout(() => {
            resolve(successResponse); 
        }, 2010);

    });
}

function dbStatusFail () {
    return new Promise(function(resolve, reject) {
        setTimeout(() => {
            reject(failResponse); 
        }, 2000);

    });
}

module.exports = {
    dbStatusSuccess,
    dbStatusFail
} 

这是我的测试。

'use strict'
const Promise = require('bluebird');
const chai = require('chai')
chai.use(require('chai-string'))
chai.use(require('chai-as-promised'));
const expect = chai.expect;
chai.should();


const healthyCheck = require('./healthyCheck');

const resp = {status:'OK'};
const resp2 ={status: 'FAIL'};

 describe('healthy-check end point', () => {

    it('should return successful response when connected to database', () => {

        return healthyCheck.dbStatusSuccess()
                            .then((res) => {
                                console.log(JSON.stringify(res, undefined, 2));
                                return expect(res).to.equal(resp);
                            }).catch( (err) => {
                                console.log(err);
                                return expect(err).to.deep.equal(resp2);
                            });


    });
 });

我还在控制台中收到错误 { AssertionError: expected { status: 'OK' } to equal { status: 'OK' }。我相信这是来自 .catch 函数的 loggin 错误。

编辑 1。 从 dbStatusSuccess 函数中删除了拒绝函数。

问题在于 complete/fail 需要 2 秒的承诺。如果setTimeout中设置的时间小于2秒,则测试通过。

嗯,我刚发现问题,你的测试很棘手。 您将超时计时器设置为 2010 毫秒,但 Mocha 默认执行时间为 2000 毫秒,因此您将始终收到 Mocha 的错误。

我仍然认为你不应该在返回的 promise 链中创建 .catch 块,它会停止 promise 链的传播。

describe('healthy-check end point', () => {

    it('should return successful response when connected to database', () => {

        return healthyCheck.dbStatusSuccess()
                            .then((res) => {
                                console.log(JSON.stringify(res, undefined, 2));
                                return expect(res).to.equal(resp);
                            });


    }).timeout(2500); //tell Mocha to wait for 2500ms
 });

您应该使用 done 回调,例如:

it('reads some file', function(done) {
  fs.readFile('someFile.json', function(err, data) {
    if (err) return done(err);
    assert(data != null, "File should exist.");
    done();
  });
});

发生的是测试('it' 函数)returns 在你的承诺解决之前;使用 done 意味着测试不会完成,直到您调用 done() 时承诺解决。

http://tobyho.com/2015/12/16/mocha-with-promises/

https://mochajs.org/#working-with-promises

  'use strict'
  const Promise = require('bluebird');
  const chai = require('chai');
  chai.use(require('chai-string'));
  chai.use(require('chai-as-promised'));
  const expect = chai.expect;
  chai.should();

  const healthyCheck = require('./healthyCheck');

  describe('healthy-check end point', function() {

    it('should return successful response when connected to database', function(done) {
      const resp = {status: 'OK'};

     healthyCheck.dbStatusSuccess()
        .then((res) => {
          console.log(JSON.stringify(res, undefined, 2));
          expect(res).to.equal(resp);
          done();
        }).catch(done);
    });
  });
  1. 在代码示例中我没有return承诺,所以我需要使用回调。在异步测试中使用回调有助于避免 Error: timeout of 2000ms exceeded
  2. 不要在 descibeit 中使用箭头函数。 More info

您测试中的默认超时似乎是 2000 毫秒。您的代码显然需要更长的时间才能完成。因此,您必须提高超时限制。如前所述 here 你不应该使用箭头函数,这样你就可以安全地访问 this.

然后你可以像这样增加超时时间:

'use strict'
const Promise = require('bluebird');
const chai = require('chai')
chai.use(require('chai-string'))
chai.use(require('chai-as-promised'));
const expect = chai.expect;
chai.should();


const healthyCheck = require('./healthyCheck');

const resp = {status:'OK'};
const resp2 ={status: 'FAIL'};

 describe('healthy-check end point', () => {

    it('should return successful response when connected to database', function() {
        this.timeout(3000);
        return healthyCheck.dbStatusSuccess()
                            .then((res) => {
                                console.log(JSON.stringify(res, undefined, 2));
                                return expect(res).to.equal(resp);
                            }).catch( (err) => {
                                console.log(err);
                                return expect(err).to.deep.equal(resp2);
                            });


    });
 });

那么您的测试应该运行符合预期。