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.