这是测试中的代码:
function timeout(): Promise<NodeJS.Timeout> {
return new Promise(resolve => setTimeout(resolve, 0));
}
async function router(publish: Publish): Promise<void> => {
await timeout();
publish('requestObject');
};
这是我的测试。如果我使用下面的try / catch,则会立即失败并返回正确的错误。
it.only('returns a valid response', (done) => {
const publish = sinon.stub();
publish.callsFake((publishResponse) => {
try {
expect(publishResponse).to.equal('wrong');
done();
} catch (error) {
done(error);
}
});
router(publish);
sinon.restore();
});
如果我删除try / catch测试时间超出:
publish.callsFake((publishResponse) => {
expect(publishResponse).to.equal('wrong');
done();
});
错误:超出5000毫秒的超时。对于异步测试和挂钩,确保调用“done()”;如果返回Promise,请确保它已解决。
我想这个承诺没有解决,因为预期会失败。所以它没有达到完成()。有没有办法让我更干净地重写这个?或者使用try / catch以适当的方式编写此测试?
我读了一个类似问题的several SO answers,他们说要确保被测代码不会吞下错误。但在我的代码中,我没有看到任何代码吞噬错误。
我通过等待测试中的代码而不是使用回调/完成结构,并使用参数期望(calledWith)而不是在虚假回调中进行期望来简化它。
我不确定为什么这会起作用而不是回调方法。
it.only('returns a valid response', async () => {
const publish = sinon.stub();
await router(publish);
expect(publish).to.be.calledWith('wrong');
sinon.restore();
});