jest-json
Jest matchers to work with JSON strings.
Setup
Note: If you're using Jest < 27.2.5, you should stick to jest-json@^1.0
.
Add jest-json
to your Jest config:
{
"setupTestFrameworkScriptFile": "jest-json"
}
Or if you're already using another test framework, create a setup file and require each of them:
require("jest-json");
// require("some-jest-library);
Motivation
Say you need to assert foo
was called with foo("url", "{'foo': 'bar', 'spam': 'eggs'}")
:
// option 1
expect(foo).toHaveBeenCalledWith(
"url",
JSON.stringify({
foo: "bar",
spam: "eggs",
})
);
This test may fail depending on how the second argument was created:
// this will pass the test:
foo(
"url",
JSON.stringify({
foo: "bar",
spam: "eggs",
})
);
// this will fail the test:
foo(
"url",
JSON.stringify({
spam: "eggs",
foo: "bar",
})
);
See this repl.it for a working example.
To fix the test you'd have to find in foo.mock.calls
the call you want, parse the JSON and call expect().toEqual({ spam: "eggs", foo: "bar" })
.
Matchers
expect.jsonMatching
In the example above, you can use the expect.jsonMatching
asymmetric matcher:
expect(foo).toHaveBeenCalledWith(
"url",
expect.jsonMatching({
foo: "bar",
spam: "eggs",
})
);
You can include other asymmetric matchers inside like:
expect.jsonMatching(
expect.objectContaining({
foo: expect.stringMatching("bar")
})
)
expect().toMatchJSON()
It's just sugar for calling JSON.parse()
and then expect().toEqual()
:
expect(json).toMatchJSON(expected);
// equivalent to:
const tmp = JSON.parse(json);
expect(tmp).toEqual(expected);