32

I am attempting to use Jest's new Property Matcher feature (since Jest 23.0.0) to match on an array of objects that contain a generated field. I have tried putting both a plain object and a matcher definition using expect.arrayContaining and expect.objectContaining like I might when matching manually. Is there any way to do this currently?

const sportsBallPeople = [
  {
    createdAt: new Date(),
    name: 'That one famous guy from Cleveland'
  },
  {
    createdAt: new Date(),
    name: 'That tall guy'
  }
];
expect(sportsBallPeople).toMatchSnapshot(<something goes here>);
Brian Adams
  • 36,719
  • 6
  • 95
  • 103
giodamelio
  • 5,295
  • 14
  • 41
  • 70
  • 1
    I don't think it is possible with current version of Jest. Looking into the code it seems like property match is only available for object snapshots, arrays can only be matched to exact copies. – Munim Munna Aug 03 '18 at 14:22
  • Would you be open to using a different approach instead of Jest's new Property Matcher feature? Since this isn't supported in the current version, I omit these properties before passing the object into expect(). – Jeff Sallans Sep 24 '18 at 15:10

4 Answers4

46

Version Info

As is noted in the question, property matchers were introduced in Jest 23.0.0. Note that apps bootstrapped with create-react-app as of today (Aug 5, 2018) are still < 23.

OBJECT

Here is an example using a property matcher for a single object:

test('sportsBallPerson', () => {
  expect(sportsBallPeople[0]).toMatchSnapshot({
    createdAt: expect.any(Date)
  })
});

The snapshot generated:

exports[`sportsBallPerson 1`] = `
Object {
  "createdAt": Any<Date>,
  "name": "That one famous guy from Cleveland",
}
`;

This will correctly match createdAt to any date and the name to exactly "That one famous guy from Cleveland".

ARRAY

To test an array of objects using property matchers use forEach to loop over the array and snapshot test each object individually:

test('sportsBallPeople', () => {
  sportsBallPeople.forEach((sportsBallPerson) => {
    expect(sportsBallPerson).toMatchSnapshot({
      createdAt: expect.any(Date)
    });
  });
});

The snapshots generated:

exports[`sportsBallPeople 1`] = `
Object {
  "createdAt": Any<Date>,
  "name": "That one famous guy from Cleveland",
}
`;

exports[`sportsBallPeople 2`] = `
Object {
  "createdAt": Any<Date>,
  "name": "That tall guy",
}
`;

forEach ensures that the objects are tested in order, and each object is properly snapshot tested as described above.

Additional Info

It is interesting to note that directly testing an array using property matchers does not work properly and has unexpected side-effects.

My first attempt to test an array was to create the following test:

test('sportsBallPeople as array', () => {
  expect(sportsBallPeople).toMatchSnapshot([
    { createdAt: expect.any(Date) },
    { createdAt: expect.any(Date) }
  ]);
});

It generated the following snapshot:

exports[`sportsBallPeople as array 1`] = `
Array [
  Object {
    "createdAt": Any<Date>,
  },
  Object {
    "createdAt": Any<Date>,
  },
]
`;

This is incorrect since the name properties are missing, but the test still passes (Jest v23.4.2). The test passes even if the names are changed and additional properties are added.

Even more interesting was that as soon as this test executed, any following tests using property matchers were adversely affected. For example, placing this test ahead of the the test looping over the objects changed those snapshots to the following:

exports[`sportsBallPeople 1`] = `
Object {
  "createdAt": Any<Date>,
}
`;

exports[`sportsBallPeople 2`] = `
Object {
  "createdAt": Any<Date>,
}
`;

In summary, directly passing an array to use with property matchers does not work and can negatively affect other snapshot tests using property matchers.

Brian Adams
  • 36,719
  • 6
  • 95
  • 103
  • 4
    Thanks for the experimentation, after some more playing around myself I came to the same conclusion. I guess I will take it up as a feature request on the Jest tracker. – giodamelio Aug 06 '18 at 16:34
  • 4
    @giodamelio can you share the feature request link, if you did create it? – Christian Rondeau Jan 24 '19 at 03:16
  • 1
    yet to look into it, but if [that](https://github.com/facebook/jest/pull/6528) MR wasnt yet in master th time of experimentation the latter option might work now. – Sam96 May 25 '20 at 16:25
2

toMatchObject works for array to because arrays are objects

expect(receivedArray).toMatchObject(expectedArray)

mehari
  • 2,521
  • 1
  • 19
  • 33
2

To apply snapshot property matcher to each array entry without creating a separate assertion for each, we may create an array with length equal to the value's length filled with the matcher definition:

it('should return first 10 notes by default', async () => {
  const noteMatcher = {
    createdAt: expect.any(String),
    updatedAt: expect.any(String),
  }
  const response = await app.inject({
    method: 'GET',
    url: `/examples/users/1/notes`,
  })
  const payload = response.json()
  const { length } = payload.data

  expect(response.statusCode).toMatchInlineSnapshot(`200`)
  expect(length).toBe(10)
  expect(payload).toMatchSnapshot({
    data: new Array(length).fill(noteMatcher),
  })
})

Will result in the following snapshot:

exports[`should return first 10 notes by default 2`] = `
Object {
  "data": Array [
    Object {
      "createdAt": Any<String>,
      "deletedAt": null,
      "id": 1,
      "note": "Note 1",
      "title": "Title 1",
      "updatedAt": Any<String>,
      "userID": 1,
    },
    Object {
      "createdAt": Any<String>,
      "deletedAt": null,
      "id": 2,
      "note": "Note 2",
      "title": "Title 2",
      "updatedAt": Any<String>,
      "userID": 1,
    },
    // 8 omitted entries
  ],
  "success": true,
}
`;
Ian Bunag
  • 21
  • 1
-1

Thanks for the tips. Often, being a test you can control the inputs making something like the following viable.

describe.only('Something', () => {
  it.only('should do something', () => {
    const x = {
      a: false,
      b: true,
      c: 157286400,
    };
    const results = functionBeingTesting(x, 84);
    expect(results[0]).toMatchInlineSnapshot({
        createdAt: expect.any(Number),
        updatedAt: expect.any(Number)
      },
      `
        Object {
          "createdAt": Any<Number>,
          "a": false,
          "b": true,
          "updatedAt": Any<Number>,
          "value": "0",
        }
      `,
    );
    expect(results[1]).toMatchInlineSnapshot({
        createdAt: expect.any(Number),
        updatedAt: expect.any(Number)
      },
      `
        Object {
          "createdAt": Any<Number>,
          "a": false,
          "b": true,
          "updatedAt": Any<Number>,
          "value": "1",
        }
      `,
    );
    expect(results[2]).toMatchInlineSnapshot({
        createdAt: expect.any(Number),
        updatedAt: expect.any(Number)
      },
      `
        Object {
          "createdAt": Any<Number>,
          "a": false,
          "b": true,
          "updatedAt": Any<Number>,
          "value": "1",
        }
      `,
    );
  });
});
cramhead
  • 927
  • 7
  • 17