Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

jest-json

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

jest-json

Jest matcher for working with JSON

  • 2.0.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

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

Keywords

FAQs

Package last updated on 09 Dec 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc