Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 30 ยท Matchers

Arrays and Objects

Test arrays and objects in Jest with toContainEqual, toHaveProperty, toMatchObject, objectContaining, arrayContaining and expect.any, with a runnable stand-in.

Real programs rarely return a single number. They return a list of users, an order with nested line items, or an API payload with an id that changes on every run. Checking the whole value with toEqual works until one field is random or irrelevant, and then your tests become noisy and brittle.

Jest has a family of matchers for exactly this: ask "does this list contain an item like this?", "does this object have a property at this path?", or "does this object include at least these fields?". This lesson covers them and the asymmetric matchers (expect.any, expect.objectContaining, ...) that let you describe a value loosely. It builds on Common Matchers and Numbers and Strings.

Real versus stand-in. The Jest code in plain blocks is real and read-only, because the site cannot run Jest. The runnable examples use a small expect written in Node for this lesson. It reproduces the idea (recursive comparison, subset comparison, placeholders) but it is not Jest's source, and Jest's error messages are richer.

Three questions about a collection

Is it in the list? toContain and toContainEqual.
Is this property there? toHaveProperty with a path.
Does it include these fields? toMatchObject and objectContaining.

Pick the loosest check that still proves your point.

1 / 2

toContain versus toContainEqual

toContain checks that an array has an item using strict equality (===). That is fine for numbers and strings, but it fails for objects, because two separate objects are never ===.

JavaScript
const fruits = ['apple', 'banana'];
expect(fruits).toContain('banana');            // passes

const users = [{ id: 1, name: 'Ada' }, { id: 2, name: 'Linus' }];
expect(users).toContain({ id: 1, name: 'Ada' });      // FAILS: different object
expect(users).toContainEqual({ id: 1, name: 'Ada' }); // passes: deep equality

Use toContainEqual whenever the items are objects or arrays. It recursively compares the item with each element until one matches. toContain also works on strings (substring) and iterables such as Set, as you saw in Numbers and Strings.

toHaveProperty

toHaveProperty checks that a property exists at a path, and optionally that it has a given value.

JavaScript
const order = {
  id: 'A-17',
  customer: { name: 'Ada', address: { city: 'London' } },
  items: [{ sku: 'pen', qty: 2 }],
};

expect(order).toHaveProperty('id');
expect(order).toHaveProperty('customer.address.city', 'London');
expect(order).toHaveProperty('items[0].sku', 'pen');
expect(order).toHaveProperty(['customer', 'name'], 'Ada');
expect(order).not.toHaveProperty('discount');

A string path uses dots and [index]. If a key itself contains a dot (for example "a.b"), use the array form, because the string form would split on the dot. The check passes for a property that exists with the value undefined, so it answers "is the key there?" rather than "is the value defined?".

toMatchObject: a subset check

toEqual demands that the object has exactly the expected fields. toMatchObject requires only that the expected fields are present and equal; extra fields in the received object are fine, and the rule applies recursively.

JavaScript
const response = {
  status: 201,
  body: { id: 9183, name: 'Ada', createdAt: '2026-01-05T10:00:00Z' },
};

expect(response).toMatchObject({ status: 201, body: { name: 'Ada' } });

Two details trip people up:

  1. Inside toMatchObject, arrays are not subset-matched. A received array must have the same length as the expected one, and each element is matched as a subset. If you want "contains these items, in any order", use expect.arrayContaining.
  2. You can also pass an array of objects to toMatchObject when the received value is an array of the same length.

Asymmetric matchers

Sometimes one field is unpredictable: a generated id, a timestamp, a random token. Asymmetric matchers are placeholders you put inside the expected value. They are "asymmetric" because only one side of the comparison (the expected value) knows how to decide a match.

Placeholder Matches
expect.any(Number) any number (also String, Boolean, Function, Object, a class, ...)
expect.anything() anything except null and undefined
expect.objectContaining({...}) an object that has at least these properties
expect.arrayContaining([...]) an array that includes all these items, in any order
expect.stringContaining('x') a string that includes x
expect.stringMatching(/re/) a string that matches the pattern

They work in toEqual, toMatchObject, toHaveBeenCalledWith and nested at any depth:

JavaScript
expect(createUser('Ada')).toEqual({
  id: expect.any(Number),
  name: 'Ada',
  token: expect.stringMatching(/^[a-f0-9]{8}$/),
  roles: expect.arrayContaining(['member']),
});

Every real field is still checked; only the unpredictable ones are relaxed. That keeps the test strict where it matters. We will use the same trick on mock calls in Mock Functions with jest.fn.

Choosing the right matcher

  • Need the value to be exactly this shape? toEqual (or toStrictEqual).
  • Care about a few fields of a bigger object? toMatchObject or expect.objectContaining.
  • Need to know whether one key or path exists? toHaveProperty.
  • Need to know an object is in a list? toContainEqual.
  • Need several items, order irrelevant? expect.arrayContaining.

A stand-in you can run

The code below implements a recursive equals with an optional subset mode, the asymmetricMatch protocol (the same idea Jest uses), and the matchers from this lesson. Each check prints PASS or FAIL. The first toContain check on objects fails on purpose, to show why toContainEqual exists.

Node.js Collection matchers from scratch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Four checks fail on purpose. toContain on an object fails because it compares references. toEqual fails when the received object has an extra field, while toMatchObject with the same data passes. The array check fails because ["a", "b", "c"] is not the same length as ["a", "b"], which surprises people who expect subset matching on arrays. The last failure shows expect.any(String) rejecting a number (our stand-in prints the placeholder as an object; Jest prints it nicely). Everything else passes.

The second example uses the same helpers on something closer to real life: an API handler that returns a new object every call, where the id and timestamp change.

JS Testing a result with unpredictable fields

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In real Jest those four console lines collapse into one assertion, using the placeholders from the table above:

JavaScript
expect(order).toMatchObject({
  id: expect.any(Number),
  createdAt: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T/),
  customer: 'Ada',
  total: 11,
});
expect(order.items).toContainEqual({ sku: 'pen', price: 2, qty: 3 });

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does expect([{ id: 1 }]).toContain({ id: 1 }) fail?

    toContain uses strict equality, so a new object literal is a different reference. toContainEqual compares by deep equality instead.
  2. 2. Which assertion passes for the received value { id: 7, name: 'Ada', admin: true }?

    toMatchObject only requires the listed fields to match, so extra fields are fine. toEqual demands the exact set of fields, and toBe compares references.
  3. 3. What is expect.any(Number) for?

    expect.any(Type) is an asymmetric matcher: it accepts any value of that type, so the rest of the object can still be checked strictly.
  4. 4. How do you check a key that itself contains a dot, such as 'a.b', with toHaveProperty?

    A string path is split on dots. The array form passes each key unchanged, so a key containing a dot works.
  5. 5. Inside toMatchObject, how are arrays compared?

    Arrays are not subset-matched. Use expect.arrayContaining when you only care that certain items are present.

Summary

  • toContain uses ===; use toContainEqual for objects and arrays inside a list.
  • toHaveProperty takes a dotted/indexed string path or an array of keys, plus an optional value.
  • toMatchObject checks a subset of fields recursively, but arrays must have equal length.
  • Asymmetric matchers (expect.any, anything, objectContaining, arrayContaining, stringMatching) relax only the unpredictable parts of an expected value.
  • Choose the loosest matcher that still proves what the test is about.

Next: Errors and Custom Matchers.