jest-expect-json

Jest testing with JSON

Usage no npm install needed!

<script type="module">
  import jestExpectJson from 'https://cdn.skypack.dev/jest-expect-json';
</script>

README

Jest Expect JSON

Do you need to test objects against json strings? Does jest expect not have all the json matchers you deserve? Are your fetch tests looking real fragile with that block of json?

Import jest-expect-json into your tests now! Built on Jest expect matchers, `jest-expect-json add useful json testing to jest!

Setup

Add jest-expect-json to your test file like so:

import 'jest-expect-json';

Methods

jsonMatching

jsonMatching parses a json string for use with expect.

fetch('url', {
    method: 'POST',
    body: '{"some": "DATA", "more": "DATA!"}',
})
expect(fetch).toBeCalledWith('url', {
    method: 'POST',
    body: expect.jsonMatching({
        some: 'DATA',
        more: expect.stringContaining('!'),
    }),
});

jsonContaining

jsonContaining parses a json string and tests the data with the appropriate -containing method;

fetch('url', {
    method: 'POST',
    body: '{"some": "DATA", "more": "unchecked data"}',
})
expect(fetch).toBeCalledWith('url', {
    method: 'POST',
    body: expect.jsonContaining({ some: 'DATA' }),
});

Notes

Having trouble with type definitions? Append to your package.json like jest-extended:

"jest": {
  "setupFilesAfterEnv": [
    "jest-expect-json"
  ]
}