I encountered a scenario where a function throws a string.
Although Jest provides the toThrow
matcher for testing functions that throw errors, it only works when an Error object is thrown.
Is there a way to test if a string is thrown using Jest?
The given code snippet:
async function funToTest(): Promise<number> {
if (Math.random()) throw 'ERROR_CODE_X';
return 10;
}
describe('funToTest', () => {
it('should throw `ERROR_CODE_X`', () => {
await expect(() => funToTest()).rejects.toThrow('ERROR_CODE_X');
});
});
produces the following result:
funToTest › should throw `ERROR_CODE_X`
expect(received).rejects.toThrow(expected)
Expected substring: "ERROR_CODE_X"
Received function did not throw
This clearly indicates that the function did not throw as expected, even though it does indeed throw.
If the string throwing part is changed to an Error (throw new Error('ERROR_CODE_X')
), then the test passes successfully.