简体   繁体   中英

how do I check if a value is in a JSON return or not?

I'm writing a test in postman where I want to check if a JSON return contains the Label called 'RegressieMapTest'. This is my script:

pm.test("Is the folder created correctly?", function(){
var jsonData = pm.response.json();
var objString = JSON.stringify(jsonData);
var obj =  JSON.parse(objString);

for (var i = 0; i < obj.Corsa.Data.length; i++){
    if (obj.Corsa.Data[i].Label == "RegressieMapTest"){
        console.log(obj.Corsa.Data[i].Label);
        pm.expect(obj.Corsa.Data.Label).to.eql("RegressieMapTest");
    }
}
pm.expect.fail();   
})

But it doesn't quite work, every time I run this script it seems like it automatically jumps to pm.expect.fail() which is weird because 'RegressieMapTest' is inside the JSON return. Postman returns the following message:

Is the folder created correctly? | AssertionError: expect.fail()

pm.respose.json() is equalent to JSON.parse you don't have to do it again

also you can use array.find method instead of looping through it

pm.test("Is the folder created correctly?", function () {
    var jsonData = pm.response.json();

    pm.expect(obj.Corsa.Data.find(elem => elem.Label === "RegressieMapTest")).to.be.not.undefined

}

if array has any element with label RegressieMapTest then it will return that data elese returns undefined, so we are validating that it will not return undefined. Meaning it has the value

Your pm.expect.fail(); always runs. You want it to run only when you don't find the field. So just add a flag in your check block.

pm.test("Is the folder created correctly?", function(){
    var jsonData = pm.response.json();
    var objString = JSON.stringify(jsonData);
    var obj =  JSON.parse(objString);

    var isFound = false;
    for (var i = 0; i < obj.Corsa.Data.length; i++){
        if (obj.Corsa.Data[i].Label == "RegressieMapTest"){
            console.log(obj.Corsa.Data[i].Label);
            pm.expect(obj.Corsa.Data.Label).to.eql("RegressieMapTest");
            isFound = true;
        }
    }

    if (!isFound) {
        pm.expect.fail();
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM