skip to Main Content

I have a response with the following body, an array.
I want to check that we have an item and only one with value IsPrimary true and salePerson of value ‘Chuck Norris’.

[
{
    "districtName": "Austria",
    "storeName": "Store6",
    "salePerson": "sdfgh",
    "isPrimary": false
},
{
    "districtName": "Austria",
    "storeName": "Store6",
    "salePerson": "dfsd",
    "isPrimary": false
},
{
    "districtName": "Austria",
    "storeName": "Store6",
    "salePerson": "Chuck Norris",
    "isPrimary": true
},
{
    "districtName": "Austria",
    "storeName": "Store6",
    "salePerson": "sdfgh",
    "isPrimary": false
}

I tried with filtering it gave me error:

data =pm.response.body;
let object_to_find = { saleperson: 'Chuck Norris' };
let result2 = data.filter(function (value) {
    return value.id == object_to_find.id && value.name == object_to_find.name;
});
console.log(result2);

Error:

Couldn't evaluate the test script:
TypeError: Cannot read properties of undefined (reading 'filter')

2

Answers


  1. To filter the array based on a specific condition (in your case, looking for an item with salePerson as ‘Chuck Norris’ and isPrimary as true), you can use the filter function as follows:

    let data = pm.response.json();
    
    let result = data. Filter(function(item) {
        return item.salePerson === 'Chuck Norris' && item.isPrimary === true;
    });
    
    console.log(result);
    

    Also ensure that the response body (pm.response.body) is properly parsed into a JavaScript object using pm.response.json() before applying the filter function and confirm that the property names used for comparison (salePerson, isPrimary) match exactly with those in the response object.

    Login or Signup to reply.
  2. @Doraemon There are two improvements needed in this particular case.

    • Response JSON is not properly formatted as array closing (square
      brace) is missing.
    • I tried to set up a mock server and tried to run
      the tests (thats where I found the array closing issue) and test can
      be improved as

    `

    pm.test("response to have object with specific values", function(){
        let object_to_find = { saleperson: 'Chuck Norris' };
        let result2 = pm.response.json().filter(function (value) {
            return value.id == object_to_find.id && value.name == object_to_find.name;
        });
        pm.expect(Array.isArray(result2)).to.eql(true);
        pm.expect(result2.length).to.greaterThan(0);
    })
    

    `

    pm.test("response is array", function(){
        var data = pm.response.json();
        pm.expect(Array.isArray(data)).toeql(true);
    })
    

    Attaching below the screenshot from local
    Test cases when array response is properly formatted

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search