samsam icon indicating copy to clipboard operation
samsam copied to clipboard

Proposal: Add `match.json(object)`

Open mantoni opened this issue 5 years ago • 1 comments

In referee, we have assert.json(actual, expected) which attempts to parse actual with JSON.parse and compares the result to expected. It would be nice to have a matcher that does the same and can be used like this:

assert.equals(actual, {
  some: 'thing',
  json: match.json({
    parsed: true
  })
});

Or with sinon assertions:

sinon.assert.calledWith(fake, match.json({
  my: 'json'
}));

I'm unsure about a naming ambiguity though: We also have assert.matchJson(actual, expectation) which parses actual with JSON.parse and compares the result to expected using the same semantics of assert.match.

How would match.json behave? And what would be the counterpart?

mantoni avatar Mar 17 '20 13:03 mantoni

Giving this some more thought, I now think the most intuitive and flexible behavior would be to pass the result of JSON.parse to match(result, arg) where arg is the argument passed to match.json(arg). It could default to match.any. This would mean:

  • match.json() succeeds on anything that is parseable JSON.
  • match.json({ key: 'value' }) succeeds when parsing the given string to an object that has key with 'value' (and any other keys).
  • match.json(true) succeeds for the string true.
  • match.json(42) succeeds for the string 42.
  • match.json('something') succeeds for any string that contains 'something'.
  • match.json(function (result) { /* ... */ }) would match if the given function returns true.

mantoni avatar Mar 07 '21 12:03 mantoni