AssertionError on Json array

I have an API Endpoint that returns a JSON array in response:

[
    {
        "status": "On Loan",
        "author": "Bettoni",
        "barcode": "123455",
        "published": "America Press, 1961.",
        "title": "Duns Scotus:",
        "dueDate": "2017-05-31"
    }
]

I have a test script that asserts for keys using Chaijs expect styling for keys
For some reason the assertion fails with an error because its checking the keys on index 1 of the data array which is obviously null.
Why does this script run assertions on the array values that are null?

pm.test("Response body must have valid keys", function () {
  var data = JSON.parse(responseBody);
  pm.expect(data).to.have.all.keys('status', 'author', 'barcode', 'published', 'title', 'dueDate');
});
AssertionError: expected [ Array(1) ] to have keys 'status', 'author', 'barcode', 'published', 'title', and 'dueDate

If I change the assertion to just the value on index 0 of the array, it works. But I don’t want to just check 1 value in the array.

pm.expect(data[0]).to.have.all.keys('status', 'author', 'barcode', 'published', 'title', 'dueDate');

Hey @harsh.parekh, the assertion fails because the expect syntax doesn’t go deep into each array item for assertions, so in your case, you’re basically expecting the array to include the specified keys, which obviously fails.

If you do not want to assert on a specified index, you can simply loop through the array and assert on each item. This is how it would look.

pm.test("Response body must have valid keys", function () {
  var data = JSON.parse(responseBody);
  data.forEach(function(item) {
      pm.expect(item).to.have.all.keys('status', 'author', 'barcode', 
      'published', 'title', 'dueDate'); 
  });
});

Feel free to reach out in case you have additional queries or if this doesn’t solve your problem.

1 Like