Here is the code snippet being tested:
function timeout(): Promise<NodeJS.Timeout> {
return new Promise(resolve => setTimeout(resolve, 0));
}
async function router(publish: Publish): Promise<void> => {
await timeout();
publish('requestObject');
};
This is my test scenario. When I use the try/catch block below, it fails immediately with the correct error.
it.only('ensures 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();
});
If I eliminate the try/catch block, the test ends up timing out with this message:
publish.callsFake((publishResponse) => {
expect(publishResponse).to.equal('wrong');
done();
});
Error: Timeout of 5000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
It seems that the promise is not resolving because the expect statement is failing. Consequently, it does not reach the done() method. Is there a better way to rewrite this test? Or is using try/catch the most appropriate approach here?
I have reviewed several Stack Overflow answers related to similar issues which suggest ensuring that the code under test does not ignore errors. However, in my code, I do not see any part where errors are ignored.