4

Using JEST I want to test if an array of objects is a subset of another array.

I want to test the following:

const users = [{id: 1, name: 'Hugo'}, {id: 2, name: 'Francesco'}, {id: 3, name: 'Carlo'}];
const subset = [{id: 1, name: 'Hugo'}, {id: 2, name: 'Francesco'}];

expect(users).toContain(subset)

I've tried the following:

describe('test 1', () => {
  it('test 1', () => {
    expect(users).toEqual(
      expect.arrayContaining([
        expect.objectContaining(subset)
      ])
    )
  });
});

But this is not correct since objectContaining doesn't accept array as param ... it works only if subset is a single object.

2 Answers 2

4

I've never tried this myself, but wouldn't it work to just say:

expect(users).toEqual(
  expect.arrayContaining(subset)
)
Sign up to request clarification or add additional context in comments.

Comments

1

You were almost there.. but this line was causing you the trouble expect.objectContaining(subset) where you are supposed to pass an object instead of an array.

As @instanceof mentioned, below code would work.. but let me share the details like what's happening here

expect(users).toEqual(
    expect.arrayContaining(subset)
)

In the above snippet, expect.arrayContaining(subset) 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.

Please note that even if you are checking for a single element, you need to pass it as an array to arrayContaining() method

Same applies for objectContaining() as well.. let's say if you want to check an Array contains an object, you can test it something like this

expect(users).toEqual(
    expect.arrayContaining([ // Note that it should be an array
        expect.objectContaining({ // Note that it should be an object
            id: 123,
        });
    ]);
);

Hope this helps :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.