Checking Exceptions
Understand how to write tests that check if functions throw exceptions using Jest's toThrow matcher. Learn to verify exception types and messages, including partial and case-insensitive matches. Gain skills to test both synchronous and asynchronous functions, ensuring robust error handling in your React app tests.
Checking that an exception is raised
The project for this lesson is similar to the last lesson, but this time searchPeople raises an exception when no matches are found.
A copy of the starter code is in the code widget below:
const people = [
{
id: 1,
firstName: "Bill",
lastName: "Peters",
},
{
id: 2,
firstName: "Jane",
lastName: "Sheers",
},
];
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
export function searchPeople(criteria) {
const found = people.filter(
(p) =>
p.firstName.toLowerCase().indexOf(criteria.toLowerCase()) > -1 ||
p.lastName.toLowerCase().indexOf(criteria.toLowerCase()) > -1
);
if (found.length === 0) {
throw Error("No people found");
}
return found;
}
export async function searchPeopleAsync(criteria) {
await wait(200);
const found = people.filter(
(p) =>
p.firstName.toLowerCase().indexOf(criteria.toLowerCase()) > -1 ||
p.lastName.toLowerCase().indexOf(criteria.toLowerCase()) > -1
);
if (found.length === 0) {
throw Error("No people found");
}
return found;
}
We use the toThrow matcher to check if an exception is raised. The way we use expect is a little different from how we have used it in previous lessons. Instead of passing the result of the function we are testing into expect, we pass the whole function into expect. This is ...