My question:
I’m trying to check response body if there’s a user which has last_name = “Holt” in following JSON file. with writing a test script in Postman
I’ve already tried:
pm.test("Last Name Holt", function () {
var jsonData = JSON.parse(responseBody);
value = pm.expect(jsonData[0].last_name).to.eql("Holt");
});
and
pm.test("Last Name Holt", function () {
const responseJson = pm.response.json();
pm.expect(responseJson.data[3].last_name).to.eql("Holt");
});
2nd code piece returns true but that’s directly looking into data[3] I want to search amongst all last_names in the file.
const jsonData = pm.response.json();
pm.test("Check last Name Holt exists.", function () {
for (let i = 0; i < jsonData.data.length; i++) {
if(jsonData.data[i].last_name === "Holt"){
console.log("The last name Holt exists.")
}else{
console.log("The last name Holt not found.")
};
}
});
If you were looking for multiple matches, you could use “filter”… It finds all the matches and stores them in a new array, so you would have to reference the array index you wanted to assert;
const jsonData = pm.response.json();
pm.test("Check last Name Holt exists.", () => {
let result = jsonData.data.filter(a => a.last_name === "Holt")
console.log("Number of matches = " + result.length)
console.log(result);
//(note the [0] for array index)
pm.expect(result[0].last_name).to.eql("Holt")
});