JSON schema matcher for jest
Want to get paid for your contributions to
jest-json-schema
? Send your resume to oneamex.careers@aexp.com
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);
});
$ npm install --save-dev jest-json-schema
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']);
}));
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.
Any contributions made under this project will be governed by the Apache License 2.0.
This project adheres to the American Express Community Guidelines. By participating, you are expected to honor these guidelines.