Thursday, September 15, 2022

Jest test array with objects without order

Hello internet!

As I was doing my regular weekday I met a surprisingly unsolved problem in Jest, namely what if I wanted to test an array's _content without order_?

So e.g. these 2 arrays should equal

[{cat: 'Takira'}, {cat: 'Inari'}]

and

[{cat: 'Inari'}, {cat: 'Takira'}].

There is an SO post about this, but it doesn't care about objects, but only primitives. Also it points to Jasmine (which does have this as a native feature), but not Jest.

So here is my generic solution to the problem

for (obj in array) {

    expect(obj).toEqual(

        expect.arrayContaining([

            expect.objectContaining(obj)

        ])

    );

}

Let's go through this step by step!

So we are looping through the array (so far so good) and then we simply expect that object to be in the array.

That's literally it.

Thank You For Coming to My TED Talk.

No comments:

Post a Comment