Skip to content

Jest expect.toThrow Not Catching Error Fix

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about Jest expect.toThrow Not Catching Error Fix. We cover key concepts, practical examples, and best practices.

Your expect(fn).toThrow() test passes when it should fail — or fails when the function clearly throws an error.

The Problem

// WRONG — function is called immediately, not passed as a callback
const throwError = () => { throw new Error('fail'); };

expect(throwError()).toThrow(); // FAILS — error is thrown during assertion setup
Error: fail

When you write expect(throwError()).toThrow(), the throwError() function is invoked immediately. The error is thrown before Jest can catch it, causing the test itself to crash.

Step-by-Step Fix

1. Pass the function as a callback

// RIGHT — pass function reference
const throwError = () => { throw new Error('fail'); };

expect(throwError).toThrow();
expect(throwError).toThrow('fail');
expect(throwError).toThrow(/fail/);

2. Test specific error messages

// RIGHT — match error message
class ValidationError extends Error {
  constructor(message) { super(message); this.name = 'ValidationError'; }
}

const validate = (input) => {
  if (!input) throw new ValidationError('Input is required');
  return input;
};

expect(() => validate(null)).toThrow('Input is required');
expect(() => validate(null)).toThrow(/required/);
expect(() => validate(null)).toThrow(ValidationError);

3. Test async functions

// RIGHT — async error testing
const asyncFail = async () => {
  throw new Error('Async error');
};

await expect(asyncFail()).rejects.toThrow('Async error');
await expect(asyncFail()).rejects.toThrow(/Async/);

4. Capture and assert on the error object

// RIGHT — inspect error properties
expect(() => validate('')).toThrow();

try {
  validate('');
} catch (error) {
  expect(error).toBeInstanceOf(ValidationError);
  expect(error.message).toBe('Input is required');
  expect(error.name).toBe('ValidationError');
}

Expected output:

PASS  tests/throw.test.js
  ✓ catches thrown error (4 ms)
  ✓ matches specific message (3 ms)
  ✓ handles async errors (5 ms)

Prevention Tips

  • Always wrap throwing code in () => { ... }
  • Test error messages with strings or regex patterns
  • Use rejects for async error testing
  • Test error types with toThrow(ErrorClass)
  • Catch and inspect errors for complex property checks

Common Mistakes with expect to throw

  1. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  2. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  3. Misunderstanding that String is [Char] with poor performance for large text operations

These mistakes appear frequently in real-world JEST code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why does toThrow fail when the function clearly throws?

You're likely calling the function instead of passing a reference. Write expect(() => fn()).toThrow() or expect(fn).toThrow() — never expect(fn()).toThrow().

Can I test for a specific error message substring?

Yes. expect(fn).toThrow('message') checks if the error message contains that string. Use regex for more precise matching: expect(fn).toThrow(/exact message/).

How do I test that a function does NOT throw?

Use expect(fn).not.toThrow() or expect(fn).not.toThrow(ErrorClass). The function is called inside expect, and the test passes if no error is thrown.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro