Angelo Dias
Angelo Dias

Reputation: 1431

Match object inside object in jest

I'm testing a function to see if, when called, it will return the proper created list.

In pseudocode, what I'd like to do is: Expect list array to have an element with the design object and, within it, a design_id that equals "payload3".

How should I write this test?

Is there a better way to do this? (other than checking if list !== empty, please)

  it('should return a list of all designs', async () => {
    // Create fake payloads
    const payload1 = {
      ...defaultPayload,
      ...{ design: { ...defaultPayload.design, design_id: 'payload1' } },
    };

    const payload2 = {
      ...defaultPayload,
      ...{ design: { ...defaultPayload.design, design_id: 'payload2' } },
    };

    const payload3 = {
      ...defaultPayload,
      ...{ design: { ...defaultPayload.design, design_id: 'payload3' } },
    };

    await createDesign.execute(payload1);
    await createDesign.execute(payload2);
    await createDesign.execute(payload3);

    const list = await listAllDesigns.execute();

    // expect(list). ????
  });

Upvotes: 0

Views: 136

Answers (1)

Elias Schablowski
Elias Schablowski

Reputation: 2812

The easiest method would be a combination of expect.arrayContaining and expect.objectContaining like so:

expect(list).toEqual(
    expect.arrayContaining([
        expect.objectContaining({
            design: expect.objectContaining({
                design_id: "payload3"
            })
        })
    ])
);

Upvotes: 1

Related Questions