Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test JSON schema in postman using tv4?

Tags:

postman

tv4

This is what i am trying, but it always passes the test even for bad results.

pm.test("Schema is valid", function () {
    var data = pm.response.json();
    var schema = {
        ...
        my schema
        ...
    };
    tv4.validate(data, schema);
});
like image 669
srayner Avatar asked Jan 04 '18 15:01

srayner


People also ask

How do I test a JSON Schema?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.


1 Answers

The reason this doesn't work is (in short) that the underlying library used by Postman (tv4) is no longer maintained. Having come across the problem earlier today, I found a solution:

tv4.validate(data, schema, false, true)

The latter two parameters are checkRecursive and banUnknownProperties. Setting these two flags as shown above make the validation work as expected.

You may also find this code snippet useful, which reports any validation errors via the console:

pm.test("Response body is valid", function() {
  var data = JSON.parse(responseBody);
  var valid = tv4.validate(data, schema, false, true);
  if (valid !== true) {
      console.log(tv4.error);
  }
  pm.expect(valid).to.be.true;
});
like image 155
Justin Finkelstein Avatar answered Sep 28 '22 17:09

Justin Finkelstein