Checking JSON body in a pm function

Hello,

I’m trying to test the response of a JSON. I’m putting it in a function so that I can use this code in other requests.

The code I’m using is:

var response = JSON.parse(responseBody);
var array_Id = 0;
var afwz_typ = response.HolidayRightsResults[0].HolidayRights[array_Id].AFWZ_TYP;

pm.test("Rechten Afwz_type "+ afwz_typ + " are ok!", function() {
pm.response.HolidayRightsResults[0].HolidayRights[array_Id].AFWZ_TYP == 07;
pm.response.HolidayRightsResults[0].HolidayRights[array_Id].BGN_DAT == "2019-01-01T00:00:00";
});

When I run this I’m getting an TypeError: Cannot read property '0' of undefined.

Hey @Coxjeffrey,

Not sure what you’re trying to do within the function but I did see that the code you have, wasn’t quite right.

The assertion syntax should look something like this:

pm.expect(HolidayRightsResults[0].HolidayRights[array_Id].AFWZ_TYP).to.equal(07);

1 Like

As @danny-dainton pointed out the mistake with your tests, you’ll need to fix that.

Also, the error that you’re receiving is because you’re calling
pm.response.HolidayRightsResults[0]

Now, pm.response is a string and you haven’t parsed it as JSON yet, and you’re trying to access a property called HolidayRightsResults of this string, which has given you undefined, then further you try to access the 0th index of this undefined value which hence gave you the error `Cannot read property ‘0’ of undefined’.

What you actually wanted is the following:

// Updated script here
var response = pm.response.json(),
  array_Id = 0,
  afwz_typ = response.HolidayRightsResults[0].HolidayRights[array_Id].AFWZ_TYP;

pm.test("Rechten Afwz_type "+ afwz_typ + " are ok!", function() {
  // Use the parsed JSON in your assertion and not `pm.response` directly
  pm.expect(response.HolidayRightsResults[0].HolidayRights[array_Id].AFWZ_TYP).to.equal(07);
  // ...
});