jest-extended icon indicating copy to clipboard operation
jest-extended copied to clipboard

JSON matcher

Open PMudra opened this issue 5 years ago • 2 comments

Feature Request

Description:

This is a copy of facebook/jest#6554 originally requested by @duailibe

There are some situations where I'd like to test a JSON string that is deep in an object. For example:

expect(fetchMock).toHaveBeenCalledWith(
  "some/url",
  expect.objectContaining({
    headers: expect.objectContaining({"Content-Type": "application/json"}),
    body: JSON.stringify({ foo: "bar", bar: "baz", baz: 3 }),
  })
);

While this works, it relies on ordering of keys in the object (which is not supposed to be reliable), and I can't use asymmetric matchers. I'd have to rewrite the test above as:

const call = fetchMock.mock.calls.find(call => heuristicToFindTheCall(call));
expect(call[1].headers).toMatchObject({"Content-Type": "application/json"});
expect(JSON.parse(call[1].body)).toMatchObject({
  foo: "bar",
  bar: "baz",
  baz: expect.any(Number)
});

Possible solution:

Again, copied from facebook/jest#6554

With this feature, the test above can be rewritten as:

expect(fetchMock).toHaveBeenCalledWith(
  "some/url",
  expect.objectContaining({
    headers: expect.objectContaining({"Content-Type": "application/json"}),
    body: expect.jsonMatching({ foo: "bar", bar: "baz", baz: expect.any(Number) }),
  })
);

PMudra avatar Mar 29 '19 12:03 PMudra

FTR I've published https://www.npmjs.com/package/jest-json. I didn't suggest it here because I wasn't interested in bringing this dependency to my projects.

Feel free to copy my implementation if anyone wants to: https://github.com/duailibe/jest-json

duailibe avatar Apr 01 '19 12:04 duailibe

I've opened a PR against your repo @duailibe but I'd be more than happy to pick this up and get the matcher into this repo :)

JamesPeiris avatar Sep 11 '19 13:09 JamesPeiris