Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
How to use `jest` to assert two object arrays has the same ids?

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'));
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Have you tried objectContaining with toContain

Something like:

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

and maybe:

expect(array1).toHaveLength(array2.length);
about 4 years ago · Santiago Trujillo Report

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!