jestjs / jest

Delightful JavaScript Testing.
https://jestjs.io
MIT License
44.27k stars 6.46k forks source link

Snapshotting Arrays with Matchers #9079

Open j opened 5 years ago

j commented 5 years ago

🐛 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.

jeysal commented 5 years ago

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

falkenhawk commented 4 years ago

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

lewchuk-span commented 4 years ago

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,
    },
  ],
}
ktutnik commented 3 years ago

Any progress on this feature?

rmclaughlin-nelnet commented 3 years ago

Just ran into this issue, would love to see a fix.

bodokaiser commented 3 years ago

Any updates?

chadmg commented 3 years ago

Any updates?

dospunk commented 2 years ago

Would love to see this feature implemented, just wanted to bump to keep the issue from getting stale

voaharybeneva commented 1 year ago

Any update?

Bast1onCZ commented 1 year ago

Any updates on this?

GuiSim commented 6 months ago

Encountered this issue today. Bummed that it hasn't been fixed in 5 years.