Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest to match every object in array

Tags:

jestjs

I want to check if every object in an array contains a property 'a' whose value is a number.


  test('a must be number always', () => {
        let response = [{ a: 'asdasd', y: 2 }, { a: 12 }];
        expect(response).toEqual(
            expect.arrayContaining([
                expect.objectContaining({ a: expect.any(Number) })
            ])
        );
    });

That above case is passing becasue jest is able to find atleast 1 object which contains a property 'a' with number. But I want every object to have number.Something similar to Array.every.

In the continuation to above, how can we match objet property to be either a number or string.

  test('a must be either number or String always', () => {
        let response = [{ a: 'asdasd', y: 2 }, { a: true }];
        expect(response).toEqual(
            expect.arrayContaining([
                expect.objectContaining({ a: expect.any(Number) or expect.any(String) or `expect a = 4` })
            ])
        );
    });
like image 947
Shadab Faiz Avatar asked Oct 15 '25 15:10

Shadab Faiz


1 Answers

I've just started using Jest and, honestly, I'm quite disappointed with its methods names and their misleading semantics ... I miss the composability and expressivity of @hapi/code or chai.

That said, you can implement your tests as follows, but I would be happy if someone shows a better way to do it:

test('a must be number always', () => {
  let response = [{ a: 'asdasd', y: 2 }, { a: 12 }];
  response.forEach(el => {
    // check each element of the array, individually
    expect(el).toEqual(expect.objectContaining({ a: expect.any(Number) }))
  })
});

// Message shows no reference to the array
// expect(received).toEqual(expected) // deep equality
// Expected: ObjectContaining {"a": Any<Number>}
// Received: {"a": "asdasd", "y": 2}

An alternative way, closer to your original code, could be the following:

test.only('a must be number always', () => {
  let response = [{ a: 'q', y: 2 }, { a: 12 }];

  expect(response).toEqual(
    // the array must NOT contain an element that does NOT contain {a: _number_}
    expect.not.arrayContaining([
      expect.not.objectContaining({a: expect.any(Number)})
    ])
  );
});


// Message references the array, but in a cryptic way:
// expect(received).toEqual(expected) // deep equality
// Expected: ArrayNotContaining [ObjectNotContaining {"a": Any<Number>}]
// Received: [{"a": "q", "y": 2}, {"a": 12}]
like image 177
Gerardo Lima Avatar answered Oct 18 '25 12:10

Gerardo Lima



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!