Coding⏱️ 2 min read📅 2026-05-31

How to Fix: How to test the type of a thrown exception in Jest

Test the type of a thrown exception in Jest with the 'throws' method.

Quick Answer: Use the 'throws' method in Jest to test the type of an exception thrown by a function, similar to AVA.

In Jest, you can use the t.error method to test the type of an exception thrown by a function.

💡 How to Use it

  • Pass the expected error type as the first argument:
it('should throw TypeError when no params were passed', (t) => {
t.error(() => {
throwError();
}, TypeError);
t.is(true, true); // You can add additional assertions here
});

Alternatively, you can use the t.throws method with a regular expression to match the error type:

it('should throw TypeError when no params were passed', (t) => {
t.throws(() => {
throwError();
}, /TypeError/);
t.is(true, true); // You can add additional assertions here
});

✅ Best Solutions to Fix It

Method 1: Using t.error

  1. Step 1: Pass the expected error type as the first argument.

Method 2: Using a Regular Expression with t.throws

  1. Step 1: Pass a regular expression that matches the expected error type.

🎯 Final Words

By using t.error or a regular expression with t.throws, you can easily test the type of an exception thrown by a function in Jest.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions