/jest-json-schema

JSON schema matcher for Jest

Primary LanguageJavaScriptApache License 2.0Apache-2.0

jest-json-schema

npm version Build Status Mentioned in Awesome Jest

JSON schema matcher for jest

Want to get paid for your contributions to jest-json-schema? Send your resume to oneamex.careers@aexp.com

Matchers included

toMatchSchema(schema)

Validates that an object matches the given JSON schema

it('validates my json', () => {
  const schema = {
    properties: {
      hello: { type: 'string' },
    },
    required: ['hello'],
  };
  expect({ hello: 'world' }).toMatchSchema(schema);
});

Installation

$ npm install --save-dev jest-json-schema

Usage

In any test file:

import { matchers } from 'jest-json-schema';
expect.extend(matchers);

Or if you want it available for all test files then set it up the same way in a test framework script file

You can pass Ajv options using matchersWithOptions and passing it your options object. The only option passed by default is allErrors: true.

import { matchersWithOptions } from 'jest-json-schema';

const formats = {
  bcp47: /^[a-z]{2}-[A-Z]{2}$/,
}

expect.extend(matchersWithOptions({ formats }));

Additionally you can also use a callback to further configure and extend the Ajv instance used by the matchers:

import ajvKeywords from 'ajv-keywords';
import { matchersWithOptions } from 'jest-json-schema';

const formats = {
  bcp47: /^[a-z]{2}-[A-Z]{2}$/,
}

expect.extend(matchersWithOptions({ formats }, (ajv) => {
  // This uses the `ajv-keywords` library to add pre-made
  // custom keywords to the Ajv instance.
  ajvKeywords(ajv, ['typeof', 'instanceof']);
}));

Contributing

We welcome Your interest in the American Express Open Source Community on Github. Any Contributor to any Open Source Project managed by the American Express Open Source Community must accept and sign an Agreement indicating agreement to the terms below. Except for the rights granted in this Agreement to American Express and to recipients of software distributed by American Express, You reserve all right, title, and interest, if any, in and to Your Contributions. Please fill out the Agreement.

License

Any contributions made under this project will be governed by the Apache License 2.0.

Code of Conduct

This project adheres to the American Express Community Guidelines. By participating, you are expected to honor these guidelines.