Home > Net >  Validate JSON Schema using Postman
Validate JSON Schema using Postman

Time:11-24

I am trying to validate my response JSON Schema, but I am always getting failed test case,

Returning JSON response is:

[
    {
        "registrationOriginDateTime": "2021-11-27T21:11:11.000Z",
        "eventId": "qc0081902",
        "badgeId": "12367",
        "customerGuid": "322245671253455",
        "products": [],
        "status": "registered",
        "demographics": []
    }
]

I am using following approach for validating schema,

var jsonSchema = {
"type": "array",
"items":{
type: "object",
properties:
{

        "registrationOriginDateTime": {"type":"string"},
        "eventId": {"type":"string"},
        "badgeId": {"type":"string"},
        "customerGuid": {"type":"string"},
        "products": {"type":"string"},
        "status": {"type":"string"},
        "demographics": {"type":"string"}

}
}
}

pm.test('Response schema type nodes verification', function() {
  pm.expect(tv4.validate(pm.response.json(), jsonSchema)).to.be.true;
});

Yet it is failing. Can someone help me on this?

CodePudding user response:

Your schema for objects "products" and "demographics" are of type: array,the items within them are strings, see below:

//set Response Body variable
var jsonData = pm.response.json();

//set Response Schema variable 
var schema = {
  "type": "array",
  "items": {
    "type": "object",
    "required": [],
    "properties": {
      "registrationOriginDateTime": {"type": "string"},
      "eventId": {"type": "string"},
      "badgeId": {"type": "string"},
      "customerGuid": {"type": "string"},
      "products": {"type": "array",
        "items": {"type": "string"}
      },
      "status": {"type": "string"},
      "demographics": {"type": "array",
        "items": {"type": "string"}
      }
    }
  }
};

//validate Response Schema against Response Body
pm.test('Response schema type nodes verification', function() {
  pm.expect(tv4.validate(jsonData, JSON.parse(schema), false, true), tv4.error).to.be.true;
});

To make the test cleaner, I would save the schema aas a value to global variables with key responseSchema, so the var schema declaration would look like the following:

var schema = pm.globals.get("responseSchema");
  • Related