Jest: Snapshotting Arrays with Matchers

Created on 22 Oct 2019  路  3Comments  路  Source: facebook/jest

馃悰 Bug Report

Creating a snapshot with array + matchers is not possible without wrapping array into an object.

To Reproduce

expect(['foo']).toMatchInlineSnapshot([expect.any(String)]);

Expected behavior

expect(['foo']).toMatchInlineSnapshot([expect.any(String)], `
  Array [
    Any<String>,
  ]
`);

Actual behavior

expect(['foo']).toMatchInlineSnapshot([expect.any(String)], `
  Object {
    "0": "foo",
  }
`);

I'm able to get by by taking my result and placing it in an object then doing the snapshot, but I feel like I should be able to snapshot an actual array with matchers.

Bug Report Needs Repro Needs Triage

All 3 comments

cc @pedrottimark noticed something when dealing with propertyMatchers in https://github.com/facebook/jest/pull/9049?

Sadly, snapshot testing with property matchers is unusable with arrays at the moment.

This also tripped me up, and I've confirmed it is still an issue on 26.2.2. My use case involves nested objects in arrays. Specifically rows that come out of a testing database where there are columns that default to the current time (and are thus outside the control of mocking).

A simple way to replicate the error:

expect([
      { id: 1, createdAt: new Date() },
      { id: 2, createdAt: new Date() },
    ]).toMatchSnapshot([
      { createdAt: new Date() },
      { createdAt: new Date() },
    ]);

The snapshot I'd expect:

Object {
  "0": Object {
    "createdAt": Any<Date>,
    "id": 1,
  },
  "1": Object {
    "createdAt": Any<Date>,
    "id": 2,
  },
}

The snapshot I get:

Object {
  "0": Object {
    "createdAt": 2020-08-06T23:54:53.133Z,
    "id": 1,
  },
  "1": Object {
    "createdAt": 2020-08-06T23:54:53.133Z,
    "id": 2,
  },
}

The object wrapping approach @j suggested has worked:

expect({ data: [
    { id: 1, createdAt: new Date() },
    { id: 2, createdAt: new Date() },
  ]}).toMatchSnapshot({ data: [
    { createdAt: expect.any(Date) },
    { createdAt: expect.any(Date) },
  ]});

Produces a snapshot of:

Object {
  "data": Array [
    Object {
      "createdAt": Any<Date>,
      "id": 1,
    },
    Object {
      "createdAt": Any<Date>,
      "id": 2,
    },
  ],
}
Was this page helpful?
0 / 5 - 0 ratings