jest-json
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

jest-json

CI Prettier npm License

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);

Readme

Keywords

Package Sidebar

Install

npm i jest-json

Weekly Downloads

12,407

Version

2.0.0

License

MIT

Unpacked Size

6.74 kB

Total Files

4

Last publish

Collaborators

  • duailibe