Checking fields in an array using a for loop

I want to check if certain fields are in the response body. I tried to use a for loop and an array with the names of these fields.

This is my test code:

const jsonData = pm.response.json();
const responce_required = [
    "guest_email",
    "status"
];
const x = responce_required.length;
// Check required fields in responce body
pm.test("Verify that all required fields in the response body are exist", () => {
    for (let i = 0; i < x; i++) {
        pm.expect(jsonData.responce_required[i]).to.exist; 
    }

Then I get the following error:
TypeError: jsonData.responce_required is undefined

What could be wrong?

This should be done using the jsonSchema assertion.

pm.test('validate JSON Schema', function() {
    pm.expect(response).to.have.jsonSchema(schema);
});

First of all, you have to define the schema as a variable. (Please use the preformatted text option in the editor so it doesn’t lose its formatting and align everything to the left).

If you need help with this, please post an example response.

1 Like

I was able to compare the entire created scheme with the response, as you wrote ( pm.expect(response).to.have.jsonSchema(schema);). But how can I compare individual fields? To compare a response field with a specific field with the value (string - name of the required field) from my array? Like

pm.expect(response).to.have.jsonSchema(schema);

JSON is based on key\value pairs. (Field = key).

If you compare the JSON Schema, it will check every key at once.

If any fields are missing, then it will fail the test.

You also have options in the schema for checking for additional fields and failing in that scenario as well.

It won’t check the values of the fields, but can check the format. Boolean, string, integer, etc.

You still haven’t included a sample response. As sometimes JSON can be complex with objects in objects, within arrays. Which can make the JSONSchema complex to get right.

1 Like

Thank you! As I understand it, this is the best way.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.