Schema Validation in Postman



  • I'm having trouble validating a schema in Postman using tv4 inside the tests tab - it is always returning a true test, no matter what I feed it. I am at a complete loss and could really use a hand - here is my example JSON Response, and my tests:

    var jsonData = JSON.parse(responseBody);
    const schema = {
    "required" : ["categories"],
    "properties": {
        "categories": {
            "required" : ["aStringOne", "aStringTwo", "aStringThree" ],
            "type": "array",
            "properties" : {
                "aStringOne": {"type": "string" },
                "aStringTwo": {"type": "null" },
                "aStringThree": {"type": "boolean" }
            }
        }
    }
    };
    
    pm.test('Schema is present and accurate', () => {
    var result=tv4.validateMultiple(jsonData, schema);
    console.log(result);
    pm.expect(result.valid).to.be.true;
    });
    

    This should return false, as all three properties are strings but its passing. Here is the example response:

    {
    "categories": [
        {
            "aStringOne": "31000",
            "aStringTwo": "Yarp",
            "aStringThree": "More Yarp Indeed"
        }
    ]
    }
    

    I'm willing to use a different validator or another technique as long as I can export it as a postman collection to use with newman in my CI/CD process. I look forward to any help you can give.



  • Hi you should first parse the schema to json, else it will be considered as empty data in some cases.

    The correct code is as below:

    let jsonData = JSON.parse(responseBody);
    schema = JSON.parse(schema); 
    

    Now you have to pass recursive validation and nondefined property check to the tv4.validation function.

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

    .....

    tv4.validate(pm.response.json(), schema, true, true)
    

    will check the json data recursively and if any new property is present in the resonse data, it fail the validation.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2