How to verify array response values in postman test? - postman

Expected Test Scenario: Need to validate the array response "Values" for the "Key: id".
I am using the test code:
pm.test("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.id).to.contains(16);
});
Getting the error:
AssertionError: object tested must be an array, a map, an object, a set, a string, or a weakset, but undefined given.
Response Body:
[
{
"id": 2,
"Name": "Hello",
"Country": "India"
},
{
"id": 4,
"Name": "thankyou",
"Country": "UK"
},
{
"id": 16,
"Name": "how are you",
"Country": "USA"
},
{
"id": 18,
"Name": "Good morning",
"Country": "Italy"
},
{
"id": 25510,
"Name": "Bonjour",
"Country": "France"
}
]
Anyone could help me in sorting out this please.

The response is not a JSON object but JSON array.
pm.response.json() will have you full json which is in the form :
[ {}, {} ]
so the JSON object with id 16 is the 3rd element in the array so first call jsonData[3] and then get id in it.
But still you will get error because what you are getting is a "integer" so cannot use contains with it . Use equal instead
pm.test("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData[2].id).to.equal(16);
});
or if you want to use contains instead , then get response as text using pm.response.text():
pm.test("Your test name", function () {
var jsonData = pm.response.text();
pm.expect(jsonData).to.contains(16);
});

Related

Find nested variable inside json payload

I'm using the find function in postman tests to save environment variables,
the find function works great when I'm looking for a variable, But I cannot get it to work when looking for variables inside an object
My payload looks something like this
{
"name": "product1",
"state": {
"DefinitionId": "productcard",
"Id": "32919b8c-984e-46c3-933d-51d3c621d4cf"
},
"status": "Done"
},
{
"name": "product2",
"state": {
"DefinitionId": "productaccount",
"Id": "4999b8c-984e-46c3-933d-55d3c621d4cf"
},
"status": "NotDone"
},
with the _find function I can find variables through the name variable
var steps = _.find(resBody, {
name: "product1",
})
pm.environment.set(steps.name, steps.state.Id);
But what If I want to search by DefinitionId?
I have tried stuffs like this
_.find(resBody, {
name.state: "product1",
}) <--did not work
_.find(resBody.state, {
name.state: "product1",
}) <--did not work [returns object object]
Thanks in advance.
This should return the an object by a DefinitionId search, if that's what you mean?
var result = resBody.find(x => x.state.DefinitionId === "productaccount");

Can not check the JSON value from the response body

I just started testing the api using the postman. I have come across one problem with the json path..
in json file I have code which looks like this
{
"users": [
{
"firstName": "UserOne",
"lastName": "One",
"subjectId": 1,
"id": 1
},
{
"firstName": "UserTwo",
"lastName": "Two",
"subjectId": 2,
"id": 2
},
{
"firstName": "UserThree",
"lastName": "Three",
"subjectId": 3,
"id": 3
}
],
"subjects": [
{
"id": 1,
"name": "SubOne"
},
{
"id": 2,
"name": "SubTwo"
},
{
"id": 3,
"name": "SubThree"
}
]
}
I start the json server with json-server --watch db.json
After that I send GET request using postman
Request URL http://localhost:3000/users
this is the body I get
[
{
"firstName": "UserOne",
"lastName": "One",
"subjectId": 1,
"id": 1
},
{
"firstName": "UserTwo",
"lastName": "Two",
"subjectId": 2,
"id": 2
},
{
"firstName": "UserThree",
"lastName": "Three",
"subjectId": 3,
"id": 3
}
]
I was trying to verify the firstName from the id 1 using the snippet code below
pm.test("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.users[0].firstName).to.eql('UserOne');
});
But the output was
FAIL Your test name | TypeError: Cannot read property '0' of undefined
I need help here because the json path users[0].firstName should give me the first index..
There is no key users in your response, so when you try to access the non-existed key, you will get error Cannot read property 'xxx' of undefined. To fix that, you just need:
pm.test("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData[0].firstName).to.eql('UserOne');
});

How do I make an User required JSON

I have a JSON file, in that three objects are available, In that 2nd and 3rd objects does not have some fields which I actually needed. In missing fields, I need to add my own values. I will provide my code below
I tried this So far:
with open("final.json") as data1:
a = json.load(data1)
final = []
for item in a:
d = {}
d["AppName"]= item["name"]
d["AppId"] = item["id"]
d["Health"] = item["health"]
d["place1"] = item["cities"][0]["place1"]
d["place2"] = item["cities"][0]["place2"]
print(final)
Error: I am getting Key Error
My Input JSON file has similar data:
[{
"name": "python",
"id": 1234,
"health": "Active",
"cities": {
"place1": "us",
"place2": "newyork"
}
},
{
"name": "java",
"id": 2345,
"health": "Active"
}, {
"name": "python",
"id": 1234
}
]
I am expecting output:
[{
"name": "python",
"id": 1234,
"health": "Active",
"cities": {
"place1": "us",
"place2": "newyork"
}
},
{
"name": "java",
"id": 2345,
"health": "Null",
"cities": {
"place1": "0",
"place2": "0"
}
}, {
"name": "python",
"id": 1234,
"health": "Null",
"cities": {
"place1": "0",
"place2": "0"
}
}
]
I see two issues with the code that you have posted.
First, you are referring to the 'cities' field in you input JSON as if it is a list when it is, in fact, an object.
Second, to handle JSON containing objects which may be missing certain fields, you should use the Python dictionary get method. This method takes a key and an optional value to return if the key is not found (default is None).
for item in a:
d = {}
d["AppName"]= item["name"]
d["AppId"] = item["id"]
d["Health"] = item.get("health", "Null")
d["place1"] = item.get("cities", {}).get("place1", "0")
d["place2"] = item.get("cities", {}).get("place2", "0")

Search Array and Set Environment Variables

My Postman response body is this:
{
"jobs": [
{
"id": "00d21be0",
"name": "IT Department"
},
{
"id": "h27da349",
"name": "Car Sales"
},
{
"id": "5d2db4125",
"name": "Grocery Clerk"
},
{
"id": "65cd0cc1d",
"name": "Accounting Department"
},
{
"id": "8462284587",
"name": "Nurse"
},
{
"id": "9fe2ff9ee4",
"name": "Astronaut"
},
{
"id": "f40cb44799",
"name": "Phone Operator"
},
{
"id": "f4e0483257",
"name": "Project Leader"
}
]
}
What I would like to do is parse this response and set an Environmental Variable for id's associated with Nurse, Astronaut, and Grocery Clerk. The rest of the info I do not need. I cannot use the array [number] because its not a guarantee they come in the same order on other systems.
Is JSON.stringify response body the way to go? How do I pull those values?
My Postman test so far is:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentalVariable("jobs", JSON.stringify(jsonData));
What you can do is parse your json body with a loop and, when you hit the names you want, you set a global variable with the corresponding id, like :
// get the response body
var jsonData = JSON.parse(responseBody);
// init counter
var loop_count = 0
for (count = 0; count < jsonData.jobs.length; count++)
{
if (jsonData.jobs[count].name == "Nurse")
{
var job_id = jsonData.jobs[count].id;
postman.setEnvironmentalVariable("env_nurse", job_id);
}
}
This is the principle.
You can do if/else for the different names you want to catch but I don't recommend it (use an array that you can expand easily).
Same thing for the environment variable name, instead of hard coding, try to generate it with respect to your element name.

Access meta reply message

My backed is giving me some information about the reply in a meta field. For example, when going to #/phoneNumbers/phonelocations/index a request to /api/phonelocations is sent, and this is the data received:
{
"meta": {
"api_action": "find_all",
"api_id": "phonelocations",
"content_type": "application/json",
"error_code": 200,
"errors": [
{
"admin_message": "",
"code": 200,
"message": ""
}
],
"message": "Successfully read phonelocations",
"success": true
},
"phonelocations": [
{
"_id": "0",
"city": "Berlin",
"count": 10,
"country": "DE",
"country_name": "Germany",
"loctype": "GEO",
"loctype_human": "Geographical number",
"subtype": "49GEO",
"subtype_human": "German geographical number",
"type": "phonelocation-faketype"
},
...
]
}
This is present in all replies coming from the backend. I would like to use the message in _reply_meta.message to display it to the user. Is there a standard way in Ember to access the meta information of the replies?
Just use store.metadataFor(type), in your case:
var meta = this.store.metadataFor('phonelocation');
// all metadata is in meta object
meta.message // => "Successfully read phonelocations"
See this in action http://jsfiddle.net/marciojunior/3vfQD/