peter
peter

Reputation: 15089

Check with Chai if an object doesn't contain any additional properties

I'm working on an API and should return based on permissions only a subset of the actual object's properties. I'm writing my tests in mocha and chai and would like to test for something like this (given res is the response object from the server and res.body contains the received JSON data):

res.body.should.not.contain.properties.except(['prop1', 'prop2.subprop'])

in which case res.body.prop1 can be any kind of object, and res.body.prop2 is only allowed to contain the property subprop - which again could be any kind of object.

Now, I could write custom functions to test this, but I thought someone else had already a similar problem and there is an extension for chai for it maybe or some other library I could use instead.

Upvotes: 1

Views: 2356

Answers (1)

Jasper Woudenberg
Jasper Woudenberg

Reputation: 1166

Out of the box, I do not think Chai offers a way to build a query like this. However, a JSON Schema is a perfect fit for testing if an object matches a certain format. Luckily, a Chai JSON Schema Plugin exists. Using that, the result looks like this:

chai.use(require('chai-json-schema'));
var bodySchema = {
    title: 'response body',
    type: 'object',
    required: ['prop1', 'prop2'],
    additionalProperties: false,
    properties: {
        prop1: {},
        prop2: {
            type: 'object',
            required: ['subprop'],
            additionalProperties: false,
            properties: {
                subprop: {}
            }
        }
    }
};
res.body.should.be.jsonSchema(bodySchema);

A short explanation:

  • The required property takes an array of required properties. If prop1 or prop2 are actually optional, remove them from this array (or leave it out alltogether).
  • The additionalProperties: false ensures no properties other than the ones defined in the properties hash are allowed.
  • prop2 contains a subschema, which can contain the same fields as the root schema and specifies the format of the sub-property.

Granted, these schema's can grow a bit large, but so would your validation function. Of course you can make the schema a true JSON file to separate it from the rest of your code.

Upvotes: 2

Related Questions