Query :
I want to check all the email id and verify expected email id is present or not but in my cases for loop is not working. It would be great if anyone help me.
{
“data”: [
{
“id”: 1,
“email”: “[email protected]”,
“first_name”: “George”,
“last_name”: “Bluth”,
},
{
“id”: 2,
“email”: “[email protected]”,
“first_name”: “Janet”,
“last_name”: “Weaver”,
},
{
“id”: 3,
“email”: “[email protected]”,
“first_name”: “Emma”,
“last_name”: “Wong”,
},
{
“id”: 4,
“email”: “[email protected]”,
“first_name”: “Eve”,
“last_name”: “Holt”,
},
{
“id”: 5,
“email”: “[email protected]”,
“first_name”: “Charles”,
“last_name”: “Morris”,
},
{
“id”: 6,
“email”: “[email protected]”,
“first_name”: “Tracey”,
“last_name”: “Ramos”,
}
],
}
My Test:
const jsonData = pm.response.json();
console.log(jsonData);
for (let i=0; i<=jsonData.data.length; i++)
{
if(pm.expect(jsonData.data[i].email).to.eql(“[email protected]”))
{
console.log(“Pass”);
break;
}
}
Error :-
AssertionError: expected ‘[email protected]’ to deeply equal ‘[email protected]’
It looks like your loop is working.
The problem is that you are asserting that the email address for all records equals Charles Morris.
As the first record is George Bluth, it fails on the very first record in the loop.
Not sure that is what you intended.
How are you determining the expected result?
Can you please confirm how you need to verify the email address.
If you just want to assert on whether Charles Morris exists somewhere in the response, then as your response seems to be an array, you can do this with the JavaScript find function and then assert on the results of the search.
Can you please use the preformatted text options when posting responses or code.
It’s really hard to read when everything is aligned to the left.
Hi @michaelderekjones ,
Thanks for response. That particular email might come to any id. So i need to search all the results.
I am new to postman . i thought using ‘for loop’ it will check all the values till it find the right one. can you please share the correct syntax.
That’s why you use the search instead of a loop.
You can search on the email address.
For example.
response = pm.response.json();
let search = (response.data.find(obj => {return obj.email === '[email protected]'})).email;
console.log(search); // [email protected]
pm.test("email = [email protected]", () => {
pm.expect(search).to.eql("[email protected]");
});
1 Like
Thank you !! it is working fine.