Search code examples
javascriptpostmanpostman-testcase

How to validate dynamic values in postman


I want to validate some mandatory fields in my JSON response body. Until now I am using a static way of testing by using hardcoded values something like this

json_response = JSON.parse(responseBody);
x=json_response
pm.expect(x).to.equal("abc"); 

But I want to rerun my test scripts so I don't want to change my tests again and again to validate the values. Could anyone please suggest how can I validate my response body.

{
    "Name": "John",
    "Contact number": 9826363660,
    "Address": "xyz"
}

As every time I will get new values in these keys "Names" "Contact number" "Address"


Solution

  •   pm.response.json().hasOwnProperty("Name")
    

    You can use hasOwnProperty to check whether the field exists

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

    Do schema validation

    var schema = {
        type: "object",
        properties: {
            "NAME": {
                "type":"string"
            },
            "ADDRESS": {
                "type":"string"
            },
            "Contact Number": {
                 "type":"number"
            }
        }
    
    };
    
        
      pm.response.to.have.jsonschema(schema)
    

    https://postman-quick-reference-guide.readthedocs.io/en/latest/schema-validation.html