5. Partial match assertions

Using Jest at an advanced level means using tools like partial matching to write tests that are better isolated and less brittle.

The partial matchers in Jest are expect.objectContaining, expect.arrayContaining, expect.anything() and expect.any().

In this section you will learn to:

  • match parts of arrays, objects, arrays of objects and objects with nested arrays
  • match a subset of a stub, spy or mock’s call arguments
  • ignore a subset of a stub, spy or mock’s call arguments with expect.any and expect.anything()

Why use partial matching in Jest?

For example if we wanted to test that the following object had the right id but didn’t care about the other fields. We could write

test('id should match', () => {
  const obj = {
    id: '111',
    productName: 'Jest Handbook',
    url: 'https://jesthandbook.com'
  };
  expect(obj.id).toEqual('111');
});

Now what if we wanted to match 2 fields whose generation was tightly coupled? With naive matching, we would do:

test('id and productName should match', () => {
  const obj = {
    id: '111',
    productName: 'Jest Handbook',
    url: 'https://jesthandbook.com'
  };
  expect(obj.id).toEqual('111');
  expect(obj.productName).toEqual('Jest Handbook');
});

With Jest’s Object partial matching we can do:

test('id should match', () => {
  const obj = {
    id: '111',
    productName: 'Jest Handbook',
    url: 'https://jesthandbook.com'
  };
  expect(obj).toEqual(
    expect.objectContaining({
      id: '111'
    })
  );
});

and for multiple fields:

test('id and productName should match', () => {
  const obj = {
    id: '111',
    productName: 'Jest Handbook',
    url: 'https://jesthandbook.com'
  };
  expect(obj).toEqual(
    expect.objectContaining({
      id: '111',
      productName: 'Jest Handbook'
    })
  );
});

The latter example seems better for readability and maintainability of the test. It has 1 assertion tests but makes sure the code is rock solid.

Jump to table of contents