Checking Exceptions
Learn various approaches for checking whether an exception is raised in a test in this lesson.
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; }
Partially implemented tests
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
...
Access this course and 1400+ top-rated courses and projects.