0

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"

  • what you want to validate , how are these field generated ? please add more details – PDHide Apr 03 '21 at 22:56
  • In the UI I have a login page where user will enter these 3 values so to test my endpoint I want to validate if Value entered in "Name" key is String, Value entered in "Contact Number" key is Integer, Value entered in "Address" key field is String – Jiya Mishra Apr 04 '21 at 11:25

1 Answers1

1
  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

PDHide
  • 18,113
  • 2
  • 31
  • 46
  • 1
    I have an endpoint which gives the above mentioned response body and I was validating the response with the test like - pm.expect("Name).to.equal("John"); and this very static way of validating by writing the name like ("John") because the value will be changed with every request instead I want something which can validate if the key generated is string. for example - pm.expect("Name").to.equal("String"); so how is it possible to check if the value generated is string or integer as for contact number it will be integer pm.expect("Contact number).to.equal(Integer); please suggest something. – Jiya Mishra Apr 04 '21 at 11:11
  • It's better to do schema validation for that – PDHide Apr 04 '21 at 12:03
  • thank you for the suggestion. I will have a look at that. – Jiya Mishra Apr 04 '21 at 13:12