Reputation: 1360
I have a simple function that throws error if input is lower than 0:
export const hoursMinutesSecondsFromSeconds = (inputSeconds) => {
if (inputSeconds < 0) {
throw new Error('illegal inputSeconds < 0');
}
let rem = Math.abs(inputSeconds);
let divisor = 3600;
const result = [];
while (divisor >= 1) {
result.push(Math.floor(rem / divisor));
rem = rem % divisor;
divisor = divisor / 60;
}
return result;
};
I am trying to test this function with an input that is lower than 0, like this:
import { hoursMinutesSecondsFromSeconds } from './timetools';
describe('hoursMinutesSecondsFromSeconds', () => {
it('throws error', () => {
expect(hoursMinutesSecondsFromSeconds(-2)).toThrowError('illegal inputSeconds < 0');
});
});
But, when I run this test, the test fails and I get an error message:
Error: illegal inputSeconds < 0
Why is this not passing the test, when it throws an error exactly like I am expecting it to throw in my test?
Upvotes: 1
Views: 261
Reputation: 3371
Looking at: https://jestjs.io/docs/en/expect#tothrowerror I expect that you need to wrap your function call in a function.
Like:
expect(() => {
hoursMinutesSecondsFromSeconds(-2);
}).toThrowError('illegal inputSeconds < 0');
Upvotes: 1
Reputation: 223104
It's impossible in JavaScript to handle an error that was thrown like expect(hoursMinutesSecondsFromSeconds(-2))
without wrapping it with try..catch
.
toThrowError
is supposed to be used with a function that is internally wrapped with try..catch
when it's called. It should be:
expect(() => hoursMinutesSecondsFromSeconds(-2)).toThrowError('illegal inputSeconds < 0');
Upvotes: 1