CodePark/ questions / Unit testing services
START PRACTICINGPRACTICE
Backend question · Backend testing › Unit testing services

Why does this test fail even though parseAmount('abc') does throw Invalid amount?

test('rejects bad input', () => {
  expect(parseAmount('abc')).toThrow('Invalid amount');
});
parseAmount('abc') throws before expect receives anything; pass a function instead: expect(() => parseAmount('abc')).toThrow(...)

The fix is to pass a function: expect(() => parseAmount('abc')).toThrow(...). toThrow must call the code itself, so it can catch the error. In this test, JavaScript runs parseAmount('abc') first, before expect gets anything. The error escapes into the test body, and Jest reports it as a failure.

"
toThrow needs an error class, not a message string" is wrong. A string argument is valid: it checks that the error message contains that text.