5.1 Object Containing

To match part of an object in Jest, we can use expect.objectContaining(partialObject).

For example, if we want to make sure our user has the right id and name, we can do:

const user = {
  id: 1,
  friends: [],
  name: 'Hugo',
  url: 'https://codewithhugo.com'
};
test('should have right id and name', () => {
  expect(user).toEqual(
    expect.objectContaining({
      id: 1,
      name: 'Hugo'
    })
  );
});

The equivalent without expect.objectContaining would be:

const user = {
  id: 1,
  friends: [],
  name: 'Hugo',
  url: 'https://codewithhugo.com'
};
test('should have right id and name', () => {
  expect(user.id).toEqual(1);
  expect(user.name).toEqual('Hugo');
});

Which will pass as follows.

npx jest src/05.01-object-containing.test.js
 PASS  src/05.01-object-containing.test.js
  ✓ should have right id and name (4ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total

This section showed how to match only part of an object.

The next section will look at how to match a subset of an array.

Jump to table of contents