JSON Schema validation is done by Tiny Validator tv4.
The assertion will fail if a schema use a
$ref to a schema that is not added before the assertion is called. Use
chai.tv4.addSchema(uri, schema) to preset schemas.
Install from npm:
$ npm install chai-json-schema
Have chai use the chai-json-schema module:
var chai = ;chai;
Install from bower:
$ bower install chai-json-schema
The module supports CommonJS, AMD and browser globals. You might need to shim
tv4's global and make sure
jsonpointer.js can be required as
var goodApple =skin: 'thin'colors: 'red' 'green' 'yellow'taste: 10;var badApple =colors: 'brown'taste: 0worms: 2;var fruitSchema =title: 'fresh fruit schema v1'type: 'object'required: 'skin' 'colors' 'taste'properties:colors:type: 'array'minItems: 1uniqueItems: trueitems:type: 'string'skin:type: 'string'taste:type: 'number'minimum: 5;//bdd styletobe;tonotbe;goodAppleshouldbe;badAppleshouldnotbe;//tdd styleassert;assert;
tv4 instance is 'exported' as
chai.tv4 and can be accessed to add schemas for use in validations:
There are other useful methods:
var list = chaitv4;var list = chaitv4;var list = chaitv4;var list = chaitv4;var schema = chaitv4;var schema = chaitv4;chaitv4;
For more API methods and info on the validator see the tv4 documentation.
This will be passed to the internal
tv4 validate call to enable support for cyclical objects. It allows tv4 to validate normal javascipt structures (instead of pure JSON) without risk of entering a loop on cyclical references.
chaitv4cyclicCheck = true;
This is slightly slower then regular validation so it is disabled by default.
Ban unknown properties
chaitv4banUnknown = true;
Passed to the internal
tv4 validate call makes validation fail on unknown schema properties. Use this to make sure your schema do not contain undesirable data.
Validate multiple errors
chaitv4multiple = true;
tv4.validateMultiple for validation instead of
tv4.validateResult. Use this if you want see all validation errors.
Due to the synchronous nature of assertions there will be no support for dynamically loading remote references during validation.
Use the asynchronous preparation feature of your favourite test runner to preload remote schemas:
// simplified example using a bdd-style async before();// as used in mocha, jasmine etc.;
Install development dependencies in your git checkout:
$ npm install
You need the global grunt command:
$ npm install grunt-cli -g
Build and run tests:
Gruntfile for additional commands.
Copyright (c) 2013 Bart van der Schoor
Licensed under the MIT license.