首页 > 解决方案 > 当 Promise 回调中的测试失败时,Mocha 超时

问题描述

如果我有以下模块:

module.exports = kontinue => {
  Promise.resolve({error:null})
    .then(o => {
      console.log('promise resolved');
      // say something goes wrong here
      if(true)
        kontinue({error:'promise resolved but something else went wrong'});
      else kontinue(o);
    })
    .catch(error => {
      console.log('caught error');
      kontinue({error:'promise rejected, or resolved but then continuation threw exception'})
    });
};


以及以下测试:

const assert = require('assert').strict;
const target = require('./the_above_code.js');

it('should not timeout', (done) => {
  target((sut) => {
    console.log('continuation called');
    assert.ok(false); // the test for sut.error === what I expected was failing
    done();
  });
});


它输出:

promise resolved
continuation called
caught error

...

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


我意识到这是因为 .catch() 正在返回一个未解决的新承诺,但这不是我在测试期间真正想要的。

我如何测试一个承诺解决的对象,如果有必要使测试失败,让 Mocha 报告失败?

也许除了延续(在使用此模块的代码中永远不会返回)之外的其他地方我可以进行测试?

我确信 monad 可以减少这里的样板代码量,但使用它们肯定会违反Kernighan 的格言

标签: mocha.jses6-promise

解决方案


推荐阅读