Testing the Type of a Thrown Exception in Jest
Last Updated :
23 Jul, 2025
Testing is a crucial aspect of software development, ensuring that code behaves as expected under various conditions. Jest, a popular JavaScript testing framework, provides powerful tools for testing different scenarios, including handling and testing exceptions. Whenever a function or method is supposed to throw an exception in some scenarios, it must be ascertained that the right kind of exception is thrown. This article will explain how to test the type of a thrown exception in Jest step by step, starting with the fundamentals of exception handling as well as the best practices of tests with thrown exceptions and short but essential notes about what should not be done.
Overview of Exception Handling in Jest
Astonishingly, exception handling in Jest is all about making your code perform optimally when things go sideways. In JavaScript, exceptions are created with the help of a throw statement and can be handled with the help of a try-catch block. Jest has two library functions to specifically verify if a function should throw an error, namely toThrow and toThrowError. These methods let you verify not only that an exception is raised but also what type of exception it is.
To illustrate this, you may have a function that is supposed to throw an error considering the inputs that it receives. With Jest, the test can be run to ensure that the error is indeed thrown. This is especially true where the type of error is of the essence, as in distinguishing between different error types such as type error, range error, or custom error.
Writing Tests for Thrown Exceptions
The writing of tests for thrown exceptions in Jest is very easy. The main technique employed is toThrow, which allows checking whether a function throws an exception or not.
Here’s a simple example:
JavaScript
function divide(a, b) {
if (b === 0) {
throw new Error('Division by zero');
}
return a / b;
}
test('throws an error when dividing by zero', () => {
expect(() => divide(10, 0)).toThrow('Division by zero');
});
Verifying Exception Types in Jest
It is crucial to verify the type of exception thrown if several exceptions may be thrown in separate circumstances. Jest enables for defining particular error types by employing the toThrowError matcher. It can be used to verify whether the instance of the error exists or not, that is, to guarantee that the right type of exception is thrown.
Here’s an example:
JavaScript
class CustomError extends Error {}
function riskyOperation() {
throw new CustomError('Something went wrong');
}
test('throws a CustomError', () => {
expect(() => riskyOperation()).toThrowError(CustomError);
});
Handling Asynchronous Code
Testing asynchronous code in Jest involves handling promises and async/await syntax. When working with exceptions in asynchronous code, one has to know how to reject the promise with the right kind of exception. Jest offers functions like rejecting. To handle this scenario, we can create a throwing exception using the Throwing() method.
Here’s an example with an asynchronous function:
JavaScript
async function fetchData() {
throw new Error('Network error');
}
test('throws an error when fetching data fails', async () => {
await expect(fetchData()).rejects.toThrow('Network error');
});
Common Mistakes and How to Avoid Them
When testing thrown exceptions in Jest, there are a few common mistakes to watch out for:
- Forgetting to wrap the function call in an arrow function: Jest requires the function call to be wrapped in an arrow function for toThrow to work correctly. For example, expect(divide(10, 0)).toThrow('Division by zero'); will not work as expected.
- Not specifying the error type: In exception types, be as specific as possible and when using toThrowError, identify the proper error class. Otherwise, the test passes for any error, not just the specific type you are looking for in the test.
- Handling asynchronous exceptions incorrectly: When testing an asynchronous code, make certain that you use the await with rejects. toThrow. A common mistake here is actually forgetting ‘await’ What this does is that the test may pass, yet, the rejected promise is not checked.
Conclusion
Testing the type of a thrown exception in Jest is a crucial part of ensuring robust and reliable code. If you learn how Jest’s built-in matchers such as toThrow, toThrowError, work, you can check on your functions to see how they behave in the event that an error occurs. Caring how you manage your synchronous and asynchronous code and avoiding these pitfalls will ensure you have better tests. Indeed, when you use Jest on your projects, the techniques described in the article will be as crucial as any other testing practice.
Similar Reads
Software Testing Tutorial Software testing is an important part of the software development lifecycle that involves verifying and validating whether a software application works as expected. It ensures reliable, correct, secure, and high-performing software across web, mobile applications, cloud, and CI/CD pipelines in DevOp
10 min read
What is Software Testing? Software testing is an important process in the Software Development Lifecycle(SDLC). It involves verifying and validating that a Software Application is free of bugs, meets the technical requirements set by its Design and Development, and satisfies user requirements efficiently and effectively.Here
11 min read
Principles of Software testing - Software Testing Software testing is an important aspect of software development, ensuring that applications function correctly and meet user expectations. From test planning to execution, analysis and understanding these principles help testers in creating a more structured and focused approach to software testing,
3 min read
Software Development Life Cycle (SDLC) Software Development Life Cycle (SDLC) is a structured process that is used to design, develop, and test high-quality software. SDLC, or software development life cycle, is a methodology that defines the entire procedure of software development step-by-step. The goal of the SDLC life cycle model is
8 min read
Software Testing Life Cycle (STLC) The Software Testing Life Cycle (STLC) is a process that verifies whether the Software Quality meets the expectations or not. STLC is an important process that provides a simple approach to testing through the step-by-step process, which we are discussing here. Software Testing Life Cycle (STLC) is
7 min read
Types of Software Testing Software testing is a important aspect of software development life-cycle that ensures a product works correctly, meets user expectations, and is free of bugs. There are different types of software testing, each designed to validate specific aspects of an application, such as functionality, performa
15+ min read
Levels of Software Testing Software Testing is an important part of the Software Development Life Cycle which is help to verify the product is working as expected or not. In SDLC, we used different levels of testing to find bugs and errors. Here we are learning those Levels of Testing in detail.Table of ContentWhat Are the Le
4 min read
Test Maturity Model - Software Testing The Test Maturity Model (TMM) in software testing is a framework for assessing the software testing process to improve it. It is based on the Capability Maturity Model(CMM). It was first produced by the Illinois Institute of Technology to assess the maturity of the test processes and to provide targ
8 min read
SDLC MODELS
TYPES OF TESTING