Course contentsShow
← JavaScript
Lesson 2678 of 2,72354. Testing in JavaScriptFree lesson

Array and Object Contains Assertions

Verifying arrays contain elements and objects contain properties with toContain and toHaveProperty.

Array and Object Contains Assertions

What you'll learn: How to verify that arrays contain specific elements and objects have expected properties using toContain and toHaveProperty.

The Core Idea

When testing collections of data, you often need to verify partial presence rather than exact equality. You might want to confirm an array includes a particular item without caring about the rest, or that an object has a certain property without asserting its entire structure. This is where containment assertions come in—they let you check for the existence of specific elements or properties.

Array Containment with toContain

The toContain assertion checks whether an array includes a specific value. It's perfect when you care that something exists in a collection but don't need to assert the entire array:

const fruits = ['apple', 'banana', 'cherry'];

expect(fruits).toContain('banana'); // ✓ passes
expect(fruits).toContain('grape');  // ✗ fails

Think of it like checking if a shopping bag contains the item you need—you don't care about everything else in the bag.

Object Property with toHaveProperty

The toHaveProperty assertion verifies that an object has a specific property, and optionally checks its value:

const user = { name: 'Alice', age: 30, role: 'admin' };

expect(user).toHaveProperty('name');           // ✓ checks existence
expect(user).toHaveProperty('name', 'Alice');  // ✓ checks value too
expect(user).toHaveProperty('email');          // ✗ property missing

You can even check nested properties using dot notation:

const config = { server: { port: 3000, host: 'localhost' } };

expect(config).toHaveProperty('server.port', 3000); // ✓ nested check

Key Takeaway: Use toContain to verify arrays include specific elements and toHaveProperty to confirm objects have expected properties—these assertions focus on partial presence rather than complete structure matching.