jest-snapshots-json-rest-api

Jest Snapshots serializer for JSON REST APIs

Usage no npm install needed!

<script type="module">
  import jestSnapshotsJsonRestApi from 'https://cdn.skypack.dev/jest-snapshots-json-rest-api';
</script>

README

jest-snapshots-json-rest-api

Build Status Coverage Status

Jest Snapshots serializer for JSON REST APIs.

Install

yarn add --dev jest-snapshots-json-rest-api

Add the following to your Jest configuration in package.json

{
  "jest": {
    "snapshotSerializers": ["jest-snapshots-json-rest-api"]
  }
}

or manually add the snapshot serializer to your test suite:

const serializer = require('jest-snapshots-json-rest-api')

// add the JSON REST API snapshot serializer
expect.addSnapshotSerializer(serializer)

Usage

The object you want to snapshot must match the following struct for the serializer to work:

{
  status: 200,
  body: {
    hello: 'world'
  }
}

Modules like supertest work out-of-the-box. Also works with LightMyRequest.

const app = require('./app')
const request = require('supertest')

test('get a user', async () => {
  const response = await request(app)
    .get('/users/')

  expect(response.status).toBe(200)
  expect(response.body.length).toBeGreaterThanOrEqual(3)

  expect(response).toMatchSnapshot()
})

This will generate the corresponding .snap file:

exports[`get a user 1`] = `{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "properties": {
    "created_at": {
      "type": "string"
    },
    "email": {
      "type": "string"
    },
    "first_name": {
      "type": "null"
    },
    "full_name": {
      "type": "string"
    },
    "id": {
      "type": "string"
    },
    "last_name": {
      "type": "null"
    },
    "status": {
      "type": "string"
    },
    "updated_at": {
      "type": "string"
    }
  },
  "type": "object"
}
`;