lundi 23 novembre 2020

Postman test error while trying to check if JSON field value is not null or undefined

I'm trying to create a test for a GET request in Postman to check if the value stored in the 'name' field of each object is different from null and undefined, but I get the following message "TypeError: Cannot read property 'name' of undefined" This is an example of the JSON body I'm working with:

[
{
 "id":1,
 "name": "Peter"
},
{
 "id":2,
 "name":"Stewie" 
},
{
 "id":3,
 "name":"Brian"
}
]

And this is the JS code for the test:

pm.test(``, function(){ 
    var response = JSON.parse(responseBody)
    var result = true

    for (i=0;i<=response.length;i++){ 
    if(!response[i].name){
     result = false}
    }
    pm.expect(result).to.eql(true)
});

Things I've tried:

  1. Getting the JSON body using var jsonData = pm.response.json(); instead of var response = JSON.parse(responseBody)
  2. Using the following condition for the IF statement: !response[i]['name']
  3. Storing the 'name' value in a global variable as follows:
    pm.test(``, function(){ 
        var response = JSON.parse(responseBody)
        var result = true
    
        for (i=0;i<=response.length;i++){ 
         pm.globals.set("variable_name", response[i]['name'];
         var name = pm.globals.get("variable_name");
        if(!name){
         result = false}
        }
        pm.expect(result).to.eql(true)
       });

Thanks!

Aucun commentaire:

Enregistrer un commentaire