Reputation: 4013
I'm writing tests using Postman BDD / Chai and have ran in to an issue testing a response that is an array.
So my API returns something along the lines of
[
{
"id": 1,
"firstName": "x",
"lastName": "y",
"dateOfBirth": "2018-04-21",
"username": "user"
},
{
"id": 2,
"firstName": "x",
"lastName": "y",
"dateOfBirth": "2018-04-21",
"username": "admin"
}
]
How do I check that the response contains certain members?
expect(response).to.have.property('id');
Does not seem to function since the response is an array. Changing response to response[0] doesn't seem to change anything either.
Suggestions?
Upvotes: 2
Views: 842
Reputation: 25881
You could just add something like this into the Tests
tab without the need to use the Postman BDD library. I've used Lodash here but you could do the same thing with native JS using a for loop
:
pm.test('Response has the ID property', () => {
_.each(pm.response.json(), (arrItem) => {
console.log(arrItem)
pm.expect(arrItem).to.have.property('id')
})
})
You could extend this to check the whole object for specfic elements - Add another line in the test like pm.expect(arrItem).to.have.property('firstName')
for example.
If you are using the PostmanBDD library you can add a for
loop to check for the id
property:
eval(globals.postmanBDD)
describe('Get id data', () => {
it('should check the id property is present', () => {
for(i=0; i < response.body.length; i++) {
console.log(response.body[i])
response.body[i].should.have.property('id')
}
})
})
Upvotes: 2