I am facing a challenge with testing an async function that is supposed to run for 2000ms before throwing an exception. Despite my efforts using Mocha / chai, the test does not seem to be working as expected.
Here's what I have attempted:
First approach:
expect(publisher.dispatchMessagelt;ExampleResponseMessagegt;(message, {}, 2 * 1000)).to.eventually.throw();
Although this test passes quickly (in 52ms), it fails to capture the exception thrown after 2 seconds. It appears that the promise of the function is not being awaited at all.
Second attempt:
expect(async () => {
await publisher.dispatchMessagelt;ExampleResponseMessagegt;(message, {}, 2 * 1000);
}).to.throw();
This time, the test fails with an error message indicating that the function did not throw an error as expected after the specified timeout period.
The desired outcome is for the test to pass when an exception is thrown after 2000ms, which falls within the designated test case timeout of 4000ms.
Additional details:
When employing the following code snippet, the test successfully captures an error being rejected by the promise (which can also be customized to reject with a specific string) within approximately 2002ms:
try {
await publisher.dispatchMessagelt;ExampleResponseMessagegt;(message, {}, 2 * 1000);
} catch (err) {
expect(err).to.be.an('Error');
}
Seeking guidance:
Can you advise on the correct approach to test if an async function throws an exception effectively?