如果我具有以下模块:
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's maxim。