expect.arrayContaining(array)

expect.arrayContaining(array) matches a received array which contains all of the elements in the expected array. That is, the expected array is a subset of the received array. Therefore, it matches a received array which contains elements that are not in the expected array.

You can use it instead of a literal value:

  • in toEqual or toBeCalledWith
  • to match a property in objectContaining or toMatchObject
  1. describe('arrayContaining', () => {
  2. const expected = ['Alice', 'Bob'];
  3. it('matches even if received contains additional elements', () => {
  4. expect(['Alice', 'Bob', 'Eve']).toEqual(expect.arrayContaining(expected));
  5. });
  6. it('does not match if received does not contain expected elements', () => {
  7. expect(['Bob', 'Eve']).not.toEqual(expect.arrayContaining(expected));
  8. });
  9. });
  1. describe('Beware of a misunderstanding! A sequence of dice rolls', () => {
  2. const expected = [1, 2, 3, 4, 5, 6];
  3. it('matches even with an unexpected number 7', () => {
  4. expect([4, 1, 6, 7, 3, 5, 2, 5, 4, 6]).toEqual(
  5. expect.arrayContaining(expected),
  6. );
  7. });
  8. it('does not match without an expected number 2', () => {
  9. expect([4, 1, 6, 7, 3, 5, 7, 5, 4, 6]).not.toEqual(
  10. expect.arrayContaining(expected),
  11. );
  12. });
  13. });