To assert that the array in the response body contains a string value in all its elements

Hi,

New to Postman and not accustomed to writing code so please help. Couldn’t find any similar post either which I could use.
I want to add an assertion to check whether a value is present in all the elements in an array.

In the below example, I have an array Fee with 3 elements.
I want to check whether all of them have a ClientName which contains “Seville” in it. How could I do that?

{
   "Fee":[
      {
         "Id":1,
         "clientName":"Seville ABC",
         "ProductName":"Product A",
         "Fee":"123"
      },
      {
         "Id":2,
         "clientName":"Seville",
         "ProductName":"Product A",
         "Fee":"123"
      },
      {
         "Id":3,
         "clientName":"Seville XYZ",
         "ProductName":"Product A",
         "Fee":"123"
      }
   ]
}

Thanks in advance.

Hey @LearningPostmanR,

Welcome to the community! :rocket:

You could try something like this:

let jsonData = pm.response.json()

pm.test('The `clientName` contains Seville', () => {
    _.each(jsonData.Fee, (item) => {
        pm.expect(item.clientName).to.include('Seville')
    })
})

It’s looping through the Fee array and then using the .include chai function the check if the clientName value, of each object, contains that string.

7 Likes

Yayyii! Thankyou so much! Worked just fine :slight_smile:

1 Like

Hey @dannydainton,

I have similar kind of requirement, I need assertion which will check clientName starts with string Seville or seville(s is in smaller case). Can you please help me with this please.

What have you tried so far?

What’s not working? :grin:

Using the text above you could modify the expect statement to add in an OR condition.

pm.test('The `clientName` starts With Seville or seville', () => {
    _.each(jsonData.Fee, (item) => {
        pm.expect(item.clientName.startsWith("Seville") || item.clientName.startsWith("seville")).to.be.true
    })
})

You could also do something with regex and check for case insensitive words or even convert the string to upper or lower case to check the word - I don’t really know your use case so it’s hard for me to say.

1 Like

Thanks for these details @dannydainton This worked for me.

I have an Array that looks like this. the FilterId is auto-generated from a PUT request.

Am storing this filterId in an environment variable filterIdFromPutRequest.

How can I use the code above to validate that the FilerID which was generated from the PUT exists in the GET which is executed After the PUT?

[
    {
        "filterId": 326994,
        "description": "3filters1",
        "details": [
            {
                "name": "cc1",
                "value": ""
            },
            {
                "name": "cc2",
                "value": ""
            }
        ]
    },
    {
        "filterId": 326997,
        "description": "3filters1_edit",
        "details": [
            {
                "name": "cc1",
                "value": ""
            }
        ]
    },
    {
        "filterId": 326999,
        "description": "Auto_APISavedSearch",
        "details": [
            {
                "name": "cc1",
                "value": ""
            }
        ]

I have the exact same situation, did you find an answer ?

Hi @dannydainton ,
I have a similar situation where I need to validate the Fee is “123” for the clientName - “Seville”. How do I accomplish that? Should I go the for loop route? I am confused and your help would be great.

1 Like

You could just do a .find() on the array and return the object which matches the condition.

From there do your assertion on the Fee property to check it matches the value you expect.

pm.test('Check the Fee for Seville', () => {
    let client = pm.response.json().Fee.find(a => a.clientName === 'Seville');
    pm.expect(client.Fee).to.equal("123");
});
2 Likes

Thank you so much Danny. It’s like seeing the nose all the time but gets ignored by the brain. :man_facepalming:

2 Likes

Sorry @achavate I didn’t see this reply but if it’s still an issue, you could do something like this I guess:

pm.test(`filterId contains ${pm.environment.get('filterIdFromPutRequest')}`, () => {
    let filterIdFromPutRequest = parseInt(pm.environment.get('filterIdFromPutRequest')),
        id = pm.response.json().filter(obj => obj.filterId === filterIdFromPutRequest);
        
    pm.expect(id[0].filterId).to.eql(filterIdFromPutRequest)
})

There are probably more efficient ways to achieve the same thing though. :grinning_face_with_smiling_eyes:

Hi @dannydainton

I have this response body-

{
    "Responses": [
        {
            "WT_Status": "Success"
        },
        {
            "NS_Status": "Success"
        }
    ]
}

I wanted to verify if NS_Status is success or not.

I tried using the below code:

let jsonData = pm.response.json()
 pm.test("Response body contains", () => {
     _.each(jsonData.Responses, (item) => {
         pm.expect(item.NS_Status).to.include('Success')
     })
 });

I’m getting an error saying Response body contains | AssertionError: object tested must be an array, a map, an object, a set, a string, or a weakset, but undefined given

What the test is doing, is running through each of the objects in the Responses array and checking the NS_Status for the value.

The problem with that approach is that NS_Status isn’t part of the first object and would be undefined, which is what the error message is telling you here.

Response body contains | AssertionError: object tested must be an array, a map, an object, a set, a string, or a weakset, but undefined given

You could use .filter() like some of the thread messages or maybe .find():

let jsonData = pm.response.json()
pm.test("Response body contains", () => {
    let result = jsonData.Responses.find(a => a.NS_Status === "Success")
    pm.expect(result.NS_Status).to.eql("Success")
});

I don’t have a lot of context for your specific use case so all I can offer is possible solutions, to get you closer to something that works for you.

2 Likes

Thank you so much :slight_smile: It is working now.

Hi @dannydainton

I have a situation where I need to validate a specific error is present in the Json response.

For example, in the below Json response, I need to verify that “errorMessage” : “My Error” is present in the response.

However, it can be anywhere in the array and not in a particular index. So I just need to verify it’s present regardless of what index it is showing up at.

Without writing a complex loop, is there an easy postman feature I can use to test this? Thank You!

[
   {
      "id":"sampleId",
      "errors":[
         {
            "errorCode":"Validation Error",
            "errorMessage":"My Error"
         },
         {
            "errorCode":"Validation error",
            "errorMessage":"Your Error"
         },
         {
            "errorCode":"Validation error",
            "errorMessage":"His Error"
         }
      ]
   }
]

Something like this would give you a true/false response if the error message is part of the errors array:

console.log(pm.response.json()[0].errors.some(a => a.errorMessage === "My Error"))

That could be made into a quick test like this:

let isErrorPresent = pm.response.json()[0].errors.some(a => a.errorMessage === "My Error");

pm.test("Verify error message", () => {
    pm.expect(isErrorPresent, "Error message not present in the array").to.be.true;
});

Thanks Danny,

This was really helpful.

1 Like

Hi @dannydainton
I have a situation where I need to validate each object in array contains clientID irrespective of value in the Json response.
Can you please help me in writing this assertion? Thanks…!!

[
    {
       
        "person": {
            "srNo": "123",
                       
        },
        
    },
    {
         "person": {
            "srNo": "234",
                       
        },
    },
    {
       "person": {
            "srNo": "234",
                       
        },
    }
]

What have you tried so far? What’s not currently working for you?