Mocha Test JSON Schema is Valid

OK so it’s important to test your JavaScript applications especially in full-stack JS. I’ve touched on this subject before when I wanted to test if JSON was returned in a valid format. So let’s take this a bit further and look at how you can use Mocha to test your JSON Schema is valid (how you require it such as required fields, required format etc). These tests follow the validation options spcified in the JSON Schema Validation organisation. In this example I’m checking the JSON returned by an RSS feed has certain properties which I require for my application to function correctly.

1. Specify your required JSON Schema

This is the JSON Schema which specifies the format of the JSON including the required properties and types.

//feed json schema
var feedSchema = {
  "title": "rss feed schema v1",
  "type": "object",
  "required": ["title", "desc", "link", "date", "image", "test"],
  "properties": {
    "title": {
       "type": "string",
    },
    "desc": {
       "type": "string"
    },
    "link": {
       "type": "string"
    },
    "date": {
       "type": "string"
    },
    "image": {
       "type": "string"
    }
  }
};

2. Write your JSON Schema test

This is a test I wrote in Mocha to validate the JSON schema above.

describe('test rss feed schema', function( done ) {

  this.timeout(15000);
  it('should work for RSS/XML 2.0', function(done) {

    var url = 'http://localhost:8011';
    request(url)
      .get('/feed/http://nodejs4u.com/?feed=rss2')
      .expect('Content-Type', /json/)
      .expect(200) //Status code
      .end(function(err,res) {
        if (err) {
          throw err;
        }
       
        //check json schema is valid for each feed item
        for (var i = 0; i < res.body.length; i++) {
            expect(res.body[i]).to.be.jsonSchema(feedSchema);
        }

        done();
      });

  });

});

As you can see the code just uses a vanilla JavaScript for loop over the response body (which should be json – and is checked so). This loops through the array of test objects returned by the http request and validates it against the schema.

Note: This is kind of an e2e test so I have increased the timeout for the test as default is 2 seconds which is not enough.

3. Run Tests

This is what a passed test looks like.
This is kind of an e2e test so I have increased the timeout for the test as default is 2 seconds which is not enough.

What does a failed test look like?

When we introduce a required property which is not present in our API response, our test fails as expected and warns us so.

What does a failed test look like?

Nice and quick. All testing should be this way.