I’m attempting to unit test my thrown error, however the test seems to be hitting the error and kicking out like normal code would.
const getDbStuff = () => {
const dbResponse = await getStuffFromDb(); // function imported from other file
if (!dbResponse) throw new Error("XXX");
// do stuff with response.
}
I have my test like:
it('should throw error when no db data', () => {
jest.spyOn(db, 'getStuffFromDb').mockResolvedValue({})
expect(() => {
getDbStuff()
}).toThrow('Some error') // Purposefully trying to make it fail
});
However when I run the test, it’s just hitting the error and quitting:
RUNS src/.../utils.test.ts
if (!dbResponse) throw new Error("XXX");
^
Error: XXX
at getDbStuff
From what I’ve read, the wrapping is the correct way to go, with the function call inside the expect(() => {}).toThrow()
, however I have also attempted this without the wrapping to the same result, ie. expect(getDbStuff()).toThrow('some error')
What is the correct way to test this?
1