Home > Back-end >  How to use `jest` to assert two object arrays has the same ids?
How to use `jest` to assert two object arrays has the same ids?

Time:04-13

How to use jest to assert objects in these two arrays have the same id?

const array1 = [{id:1,name:'a'},{id:2,name:'b'}]
const array2 = [{id:1},{id:2,name:'b'}]

for now, I am using method like this I think it isn't good.

expect(_.map(array1, 'id')).toEqual(_.map(array2, 'id'));

CodePudding user response:

The verbosity of the sample below increases readability. And saves you from using lodash. It uses arrayContaining and objectContaining from Jest.


test('states right thing', () => {

const array1 = [{id:1,name:'a'},{id:2,name:'b'}]
const array2 = [{id:1},{id:2,name:'b'}]
  
array2.forEach(object => {        // 1
  expect(array1).toEqual(         // 2
    expect.arrayContaining([      // 3
      expect.objectContaining({   // 4
        id:  object.id            // 5
      })
    ])
  )
});
});

The above reads as:

  1. for each object in array2
  2. you expect that your Array1 equals
  3. an Array that contains
  4. an Object that contains
  5. an id property matching the object from array2

It was inspired by this medium blogpost. You can paste and test it on jest playground.

CodePudding user response:

Have you tried objectContaining with toContain

Something like:

array1
  .forEach(
    ({ id }) => expect(array2).toContain(expect.objectContaining({ id }),
  );

and maybe:

expect(array1).toHaveLength(array2.length);
  • Related