5.2 Array Containing

Jest Simple Array partial match with expect.arrayContaining

To match part of an Array in Jest, we can use expect.arrayContaining(partialArray).

For example, if we want to make sure our oddArray has the right odds numbers under 10, we can do:

const oddArray = [1, 3, 5, 7, 9, 11, 13];
test('should start correctly', () => {
  expect(oddArray).toEqual(expect.arrayContaining([1, 3, 5, 7, 9]));
});

The equivalent without expect.arrayContaining would be:

const oddArray = [1, 3, 5, 7, 9, 11, 13];
test('should start correctly', () => {
  expect(oddArray).toContain(1);
  expect(oddArray).toContain(3);
  expect(oddArray).toContain(5);
  expect(oddArray).toContain(7);
  expect(oddArray).toContain(9);
});

Which yields the following test output.

npx jest src/05.02-array-containing.test.js
 PASS  src/05.02-array-containing.test.js
  ✓ should start correctly (4ms)

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

This section showed how to match subset of elements of an array.

The next section will look at how to use arrayContaining and objectContaining in tandem.

Jump to table of contents