GithubHelp home page GithubHelp logo

chai-json-schema's Introduction

chai-json-schema

npm: build:? dependencies:? dependencies:? devDependencies:?

Chai plugin with assertions to validate values against JSON Schema v4.

Assert both simple values and complex objects with the rich collection of validation terms (examples).

For general help with json-schema see this excellent guide and usable reference.

Notes

JSON Schema validation is done by Tiny Validator tv4.

It seems that tv4 is not actively developed anymore, nor does it support versions of JSON schema after draft-04. However this chai plugin will use tv4 as its backend for the forseeable future. If you want newer versions of the JSON-schema or more performance you could look at using ajv in conjunction with chai-json-schema-ajv

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.

JSON Schema's main use-case is validating JSON documents and API responses, but it is also a powerful way to describe and validate any JavaScript value or object.

Usage

server-side

Install from npm:

$ npm install chai-json-schema

Have chai use the chai-json-schema module:

var chai = require('chai');
chai.use(require('chai-json-schema'));

browser-side

Using globals:

Include chai-json-schema after jsonpointer.js, Tiny Validator tv4 and Chai:

<script src="jsonpointer.js"></script>
<script src="tv4.js"></script>
<script src="chai.js"></script>
<script src="chai-json-schema.js"></script>

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 'jsonpointer'.

Assertions

jsonSchema(value, schema)

Validate that the given javascript value conforms to the specified JSON Schema. Both the value and schema would likely be JSON loaded from an external datasource but could also be literals or object instances.

var goodApple = {
  skin: 'thin',
  colors: ['red', 'green', 'yellow'],
  taste: 10
};
var badApple = {
  colors: ['brown'],
  taste: 0,
  worms: 2
};
var fruitSchema = {
  title: 'fresh fruit schema v1',
  type: 'object',
  required: ['skin', 'colors', 'taste'],
  properties: {
    colors: {
      type: 'array',
      minItems: 1,
      uniqueItems: true,
      items: {
        type: 'string'
      }
    },
    skin: {
      type: 'string'
    },
    taste: {
      type: 'number',
      minimum: 5
    }
  }
};

//bdd style
expect(goodApple).to.be.jsonSchema(fruitSchema);
expect(badApple).to.not.be.jsonSchema(fruitSchema);

goodApple.should.be.jsonSchema(fruitSchema);
badApple.should.not.be.jsonSchema(fruitSchema);

//tdd style
assert.jsonSchema(goodApple, fruitSchema);
assert.notJsonSchema(badApple, fruitSchema);

Additional API

The tv4 instance is 'exported' as chai.tv4 and can be accessed to add schemas for use in validations:

chai.tv4.addSchema(uri, schema);

There are other useful methods:

var list = chai.tv4.getMissingUris();
var list = chai.tv4.getMissingUris(/^https?:/);

var list = chai.tv4.getSchemaUris();
var list = chai.tv4.getSchemaUris(/example.com/);

var schema = chai.tv4.getSchema('http://example.com/item');
var schema = chai.tv4.getSchema('http://example.com/item/#sub/type');

chai.tv4.dropSchemas();

For more API methods and info on the validator see the tv4 documentation.

Non-standard tv4 properties

Cyclical objects

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.

chai.tv4.cyclicCheck = true;

This is slightly slower then regular validation so it is disabled by default.

Ban unknown properties

chai.tv4.banUnknown = 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

chai.tv4.multiple = true;

Call tv4.validateMultiple for validation instead of tv4.validateResult. Use this if you want see all validation errors.

Remote references

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.

before(function (done) {

  // iterate missing
  var checkMissing = function (callback) {
    var missing = chai.tv4.getMissingUris();
    if (missing.length === 0) {
      // all $ref's solved
      callback();
      return;
    }
    // load a schema using your favourite JSON loader
    // (jQuery, request, SuperAgent etc)
    var uri = missing.pop();
    myFavoriteJsonLoader.load(uri, function (err, schema) {
      if (err || !schema) {
        callback(err || 'no data loaded');
        return;
      }
      // add it
      chai.tv4.addSchema(uri, schema);
      // iterate
      checkMissing(callback);
    });
  };

  // load first instance manually
  myFavoriteJsonLoader.load(uri, function (err, schema) {
    if (err || !schema) {
      done(err || 'no data loaded');
      return;
    }
    // add it
    chai.tv4.addSchema(uri, schema);

    // start checking
    checkMissing(done);
  });
});

History

See Releases.

Build

Install development dependencies in your git checkout:

$ npm install

You need the global grunt command:

$ npm install grunt-cli -g

Build and run tests:

$ grunt

See the Gruntfile for additional commands.

License

Copyright (c) 2013 Bart van der Schoor

Licensed under the MIT license.

chai-json-schema's People

Contributors

bartvds avatar bitdeli-chef avatar greenkeeper[bot] avatar jrschild avatar keithamus avatar niklv avatar prestonvanloon avatar roelandvanbatenburg avatar snowmac avatar sverweij avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chai-json-schema's Issues

chai-json-schema needs a new owner

I've completely crashed out of the node loop so this module desperately needs a new owner.

If anyone wants to adopt please leave a message and we can arrange ownership transfer of repos and package as per npm guidelines.

peerDependencies error

I check your package.json, the peerDependencies shows

  "peerDependencies": {
    "chai": ">= 1.6.1 < 4"
  }

But when I run npm install chai-json-schema, it gives error:

npm ERR! Darwin 15.0.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "chai-json-schema" "--save"
npm ERR! node v6.0.0
npm ERR! npm  v2.15.1
npm ERR! code EPEERINVALID

npm ERR! peerinvalid The package [email protected] does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants chai@>= 1.6.1 < 3

have no idea~

Nested schema objects raise "schema missing"

Hi, I'm trying to validate a complex schema. Some of my defined objects reference other defined objects, so there are nested references. Where these nested references are used, I get an error saying the schemas are missing. If I use a JSON schema validator, it confirms that my schema is valid.

Is there a way to have nested references?

Here is a simplified example:

{
    "properties": {
        "questions": { "$ref": "#/definitions/questions" }
    },
    "definitions": {
        "answers": {
            ...
            "id": "answers"
        },
        "questions": {
            "properties": {
                "answers": {
                    "type": "array",
                    "items": { "$ref": "#/definitions/answers" }
                },
                ...
            },
            "id": "questions"
        }
    }
}

All the top level definitions (like questions) work fine. And if instead of a reference to answers, I just say "type": "object", the error goes away.

Newer drafts of JSON Schema

Hey there! JSON Schema draft 4 is pretty old now. The project is currently on draft 7, most tools around support at least draft 6.

Instead of using tv4 which is also only support draft 4, you could use another validator which is keeping up to date. For example, AJV has support for draft 4, 5, 6 and 7, so that should help, and it'll make updates easier in the future - especially as you have greenkeeper. It'll just let you know when a new version is out, with new drafts. πŸ™Œ

I don't use Chai enough to be able to justify working on this sadly, otherwise I'd be happy to turn this into a PR. If you have any questions I'm all ears. :)

Not compatible with chai 4?

Hi @JrSchild - thanks for maintaining this chai plugin. It's very useful and should be a mandatory consideration for any project doing stuff with json and chai.

I've recently upped chai to version 4, and when installing chai-json-schema npm warns The package [email protected] does not satisfy its siblings' peerDependencies requirements! (see travis jobs 99.1 - 99.3 and the PR greenkeeper made to up chai).

On npm versions < 3 (those distributed with node 4 and 0.x) this breaks any build using chai-json-schema.

I've forked chai-json-schema, changed the chai peerDependencies range to >= 1.6.1 < 5, upped the chai dependency to 4.0.2 and ran the test suite => works OK.

  1. Would you be willing to either make these changes or accept mine as a pull request?
  2. In #26 I see there's some chores for this project that need doing. I'm willing to pick up some of these + the request @keithamus has for changing some build/ code quality tooling to chaijs guidelines. Would you be OK with that?

An in-range update of grunt-cli is breaking the build 🚨

The devDependency grunt-cli was updated from 1.3.1 to 1.3.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

grunt-cli is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 2 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Roadmap next major release (v2.0?)

At least the following things should happen before the next release. I think having a better integration with Enrise's team ensures code quality, process management and release cycles. For now this project is mostly maintenance and making sure everything is up to date with today's standards.

  • Resolve current tickets
  • Discuss other things to do for a major release
  • Rewrite tests
  • eslint instead of jshint
    • Update styling
    • Grunt & Travis
  • .editorconfig file
  • Test coverage integration
  • Run travis with more modern versions of node
    • Update package.json to support newer versions
    • Drop old legacy versions?
  • Update labels for better integration with the team
  • Release minor version on NPM (1.3.0)
  • Discuss receiving more control over the project so we can manage our team internally
  • Review the commits that I made yesterday
  • Update (dev)dependencies
  • Update peerDependencies for compatibility with chai 3.0+
  • Indentation: two spaces instead of tabs
  • Fix the tests
  • Merge PR's
  • Update buttons and such in README
  • Drop support for node 0.10
  • Update bower.json

TypeError during body check

From time to time I have problem with circular objects.

     TypeError: Converting circular structure to JSON
      at Object.stringify (native)
      at valueStrim  .... node_modules/chai-json-schema/index.js:53:17 # <--- here
      at ...

Maybe because at this line the value is a current response object (not object's body)?

Interesting, that response validation pass if I use tv4 object directly, so I have no errors and no missing schemas.

type property in schema conflicts with data type

Following Schema always fails to validate, because I have property named type in my schema.

{ "type": "array", "items": { "_id": { "type": "string" }, "name" : { "type": "string" }, "bankId" : { "type": "string" }, "type" : { "type": "string" }, } }

An in-range update of grunt-cli is breaking the build 🚨

Version 1.3.0 of grunt-cli was just published.

Branch Build failing 🚨
Dependency grunt-cli
Current Version 1.2.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

grunt-cli is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 11 commits.

  • 89ab5d7 Merge pull request #120 from gruntjs/tag-1.3.0
  • 28e8220 Fix node versions and CI
  • ebd818b Release v1.3.0
  • eaf78d6 Merge pull request #117 from gruntjs/liftoff
  • 98ba9e6 Use ~ for deps and update v8flags to 3.0.2
  • 8ae6299 Fix completions to use old Grunt style for now
  • 0c5f397 Fix version and help with no gruntfile
  • ea01dc5 Include grunt-cli version with --version
  • 7b8cb3f Implement liftoff into grunt-cli
  • 7f6298e Merge pull request #104 from paladox/patch-3
  • ccb75a6 Update grunt to 1.0.1

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Silently passes when val is a String

Overview

If an object is passed as a string, instead of as an object, the validation will unconditionally pass.
This is a problem when an HTTP payload is passed directly (as a string) to assert.jsonSchema()
Maybe should throw an exception, or parse as JSON before passing to chai.Assertion()?

Test Case

const chai = require('chai');
const assert = chai.assert;
chai.use(require('chai-json-schema'));

const testSchema = {
    required: ['walletAddress'],
    properties: {
        walletAddress: {
            type: 'string'
        }
    }
};

assert.jsonSchema({}, testSchema); // Fails correctly as expected
assert.jsonSchema("{}", testSchema); // DOES NOT FAIL

See

new chai.Assertion(val, msg).to.be.jsonSchema(exp);

An in-range update of grunt-mocha is breaking the build 🚨

Version 1.0.5 of grunt-mocha was just published.

Branch Build failing 🚨
Dependency [grunt-mocha](https://github.com/disqus/grunt-mocha)
Current Version 1.0.4
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

grunt-mocha is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build failed Details

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Update to use chai 2.x

So far chai-version is limited to < 2 would it be possible to update it to use 2.x (2.0.0 has been release last month with a couple of fixes)

Print multiple errors

In many cases will be great when assertion prints all found errors in json. For that option library need to use tv4.validateMultiple method.
Is there any workaround to do this?

Negation swallows missing schema errors

Consider this:

const schema = {
  anyOf: [
    {
      "enum": 'some value'
    },
    {
      $ref: 'invalid external schema reference'
    }
  ]
};

expect('invalid value').not.to.be.jsonSchema(schema);
expect('some value').not.to.be.jsonSchema(schema);

Expected behaviour:

Test fails with missing schema error.

What happens instead:

The test will pass no matter what value is checked against schema.

date-time format validation

Apologies if this is a dupe related to the sub-error issue. The following succeeds (when it shouldn't) with chai-json-schema yet fails (as expected) with the node jsonschema library:

const schema = 
{
    type:"object",
    properties:
    {
        exampleDate:
        {
            type:"string",
            format:"date-time"
        }
    }
};

const mock = 
{
    exampleDate: "erroneous date value"
};

mock.should.be.jsonSchema(schema);

An in-range update of grunt is breaking the build 🚨

Version 1.0.2 of grunt was just published.

Branch Build failing 🚨
Dependency grunt
Current Version 1.0.1
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

grunt is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Commits

The new version differs by 27 commits.

  • ccc3163 v1.0.2
  • e7795dc Remove iojs from test matrix (#1622)
  • a6a133b Remove deprecation warning for coffeescript (#1621) r=@vladikoff
  • 06b377e https links to webchat.freenode.net and gruntjs.com (#1610)
  • 7c5242f Use node executable for local grunt bin for Windows support
  • f6cbb63 Oh right, Windows isnt bash
  • a9a20da Try and debug why appveyor is failing on npm
  • 48bba6c Move to the test script to avoid npm was unexpected at this time.
  • 6b97ac0 Try to fix appveyor script
  • 19003ba For appveyor, check node version to decide whether to install npm@3
  • 3fcf921 Install npm@3 if npm version is npm 1 or 2
  • 77fc157 Use the local version of grunt to run tests
  • 400601a Updating devDependencies
  • 6592ad1 Update travis/appveyor to node versions we support
  • b63aeec Dont manually install npm, use the version each node version corresponds with

There are 27 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of mocha is breaking the build 🚨

Version 3.5.1 of mocha just got published.

Branch Build failing 🚨
Dependency mocha
Current Version 3.5.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As mocha is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build failed Details

Release Notes v3.5.1

3.5.1 / 2017-09-09

πŸ“° News

  • πŸ“£ Mocha is now sponsoring PDXNode! If you're in the Portland area, come check out the monthly talks and hack nights!

πŸ› Fixes

  • #2997: Fix missing xit export for "require" interface (@solodynamo)
  • #2957: Fix unicode character handling in XUnit reporter failures (@jkrems)

πŸ”© Other

Commits

The new version differs by 14 commits.

  • 4070a44 Release v3.5.1
  • 466ba73 update CHANGELOG.md for v3.5.1 [ci skip]
  • 1cc0fc0 import/require xit, fixes #2972
  • 74fa66f update nyc to latest; remove workaround in travis script
  • aa52933 update coveralls strategy; closes #2984
  • 73a5338 Spelling (#2981)
  • 9f403bf Add utils.escape tests and fix unicode escaping
  • 800acbc whitelist "developer-experience" tag for stalebot [ci skip]
  • 5895671 Added issue, pull request templates. (#2869)
  • 075bd51 Merge pull request #2918 from mochajs/no-shell-test
  • 8710438 Work around Node 0.10 Windows flake when testing
  • 13b8340 Ensure that compiler lookup works and not just that transpilation works (#2922)
  • 26d337a Add tests for double-star behavior
  • c0e6b68 Eliminate glob.sh

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.