Home > Back-end >  Jest test assertion, expect a nested object
Jest test assertion, expect a nested object

Time:06-07

When I do the below expect in jest with native test

expect(mockOnChange).toHaveBeenCalledWith({
     order_type: expect.arrayContaining(['1']),
     number: '',
     ouser_ids: expect.arrayContaining(['user_id1']),
     payment_type: expect.arrayContaining(['2']),
     start_date: old_Date,
     end_date: current_date,
     state: 'all',
    });

I'm getting the following error

   Object {
                "end_date": "2022/06/07",
                "number": "",
            -   "order_type": ArrayContaining [
                "order_type": Array [
                  "1",
                ],
            -   "ouser_ids": ArrayContaining [
                "ouser_ids": Array [
                  "user_id1",
            -   ],
            -   "payment_type": ArrayContaining [
            -     "2",
                ],
                "payment_type": Array [],
                "start_date": "2022/06/01",
                "state": "all",
              },

I have also tried without expect.arrayContaining() still getting the same error I'm I doing this wrong?

CodePudding user response:

You can't use expect.arrayContaining inside the properties of an object that you are expecting. You will need to use an alternative approach as follows:

const objectCalledWith = mockOnChange.mock.calls[0][0];
expect(objectCalledWith.order_type).toEqual(expect.arrayContaining(['1']));
// and so on for the other property values...

Explanation:

mock.calls contains all of the calls made on mockOnChange, where we specifically choose to access the first call via [0]. The second [0] retrieves the first argument that the mockOnChange function was called with and we assign it to objectCalledWith variable. We can then use this variable to inspect and validate its properties using the expect matchers as necessary.

  • Related