2

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?

5
  • you just want to make sure that all of your response objects have id ? Commented Apr 21, 2018 at 20:37
  • @GeorgeBailey No, I want to check more members but that was just an example. Main question is how to access the objects within the array. Commented Apr 21, 2018 at 20:39
  • loop through it. .map etc Commented Apr 21, 2018 at 20:40
  • @GeorgeBailey Would this be supported by Postman BDD? Commented Apr 21, 2018 at 20:42
  • You’ll need to loop through the data to assert that the different properties are in the array. Is there a reason you’re using Postman BDD over the newer builtin tests feature with all the pm.* functions? Commented Apr 21, 2018 at 21:45

1 Answer 1

2

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')
    })
})

enter image description here

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')
      }
  })
})

Postman

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.