Skip to content
Advertisement

Postman – I want to check a value to be inside an array

I am writing a postman test in JavaScript to assert the scenario below. I have an id 1111 and the response returns an array of ids. I want to write a test to match 1111 to be in one of the ids in the array.

I have tried to use the include function i.e.

pm.test("The response contains a valid id in the response", function() { 
    pm.expect(jsonData.results[0].totalId.children).to.include("1111");
});

{
    "totalId": "0000",
    "children": [{
            "id": "888"
        },
        {
            "id": "3323"
        },
        {
            "id": "1111"
        }
    ]
}  

Any suggest.

Advertisement

Answer

You’re trying to check the value from the array children, hence, you should not use the .totalId.children, instead you have to do is jsonData.results[0].children.

As you trying to check the value from the object of an array, you need add custom JavaScript logic to check the values of id param.

Here is the function you can use in your test script.

function _isContains(json, keyname, value) {
return Object.keys(json).some(key => {
        return typeof json[key] === 'object' ? 
        _isContains(json[key], keyname, value) : key === keyname && json[key] === value;
    });
}

The function _isContains checks the value and key name for the each object from the array.

Now you can pass needed input to the function in your test case.

pm.test("The response contains a valid id in the response", function () {
    pm.expect(_isContains(jsonData.children, "id" ,"1111")).to.be.true;
});

This will check from the array of the object with the key id and value 1111, if it’s available then it will returns true, otherwise returns false.


Final Test Script

var jsonData = pm.response.json();

pm.test("The response contains a valid id in the response", function () {
    pm.expect(_isContains(jsonData.children, "id" ,"1111")).to.be.true;
});

function _isContains(json, keyname, value) {
 return Object.keys(json).some(key => {
        return typeof json[key] === 'object' ? 
        _isContains(json[key], keyname, value) : key === keyname && json[key] === value;
    });
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement