Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

102
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda