Skip to content

Expected to Throw but Did Not

Error message

                Expected the function to throw an error, but it did not throw
              

Quick summary

The test expected the code to throw an error, but it didn't. Either the code should throw but doesn't (a bug), or the test expectation is wrong.

Why this happens

  • The code was supposed to throw but doesn't — missing error handling.

  • The inputs don't trigger the error condition.

  • The error is caught internally and not re-thrown.

  • The test expectation is wrong — the function shouldn't throw in this scenario.

Minimal example

✗ Broken code
function divide(a, b) {
  return a / b; // doesn't throw on division by zero (returns Infinity)
}
test('throws on zero', () => {
  expect(() => divide(1, 0)).toThrow(); // fails — no throw
});
✓ Fixed code
function divide(a, b) {
  if (b === 0) throw new Error('Division by zero');
  return a / b;
}
test('throws on zero', () => {
  expect(() => divide(1, 0)).toThrow('Division by zero');
});

Add the missing throw statement so the function properly rejects division by zero.

How to diagnose

  • Check if the code has the error condition that should trigger the throw.

  • Verify the test inputs actually trigger the error path.

  • Check if a try/catch inside the function swallows the error.

  • Review the function's specification — should it throw in this case?

How to fix

  • If the code should throw, add the missing throw statement.

  • If the inputs don't trigger the error, use inputs that do.

  • If the error is caught internally, re-throw it or test the caught behavior instead.

  • If the function shouldn't throw, remove the toThrow assertion.

How to prevent

  • Test both success and error paths for functions that can throw.

  • Use clear error messages when throwing to aid debugging.

Related Resources

Related Glossary

Related Lessons

← Back to language