Search⌘ K
AI Features

Checking Arrays

Explore how to use Jest matchers to check arrays in React tests. This lesson helps you verify array length, compare array contents, and check for items, including objects, ensuring robust automated testing.

Checking the length of the array

The project for this lesson contains a function called searchPeople, which returns matched people objects in an array for some criteria. A test has been partially implemented that checks whether the correct array is returned when a first name is passed as the criteria.

A copy of the starter project 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 async function searchPeople(criteria) {
  await wait(200);
  const found = people.filter(
    (p) =>
      p.firstName.toLowerCase().indexOf(criteria.toLowerCase()) > -1 ||
      p.lastName.toLowerCase().indexOf(criteria.toLowerCase()) > -1
  );
  return found;
}
Partially implemented test

As an exercise, use the toBe matcher in the test to check the people array ...