Search code examples
javascriptpostman-testcase

Postman: How to dynamically validate JSON value without using a switch statement


I want to dynamically validate the value of JSON request parameters without the use of switch statement

I tried the code below which works fine but it is not optimized as I have to create a case for each field I am validating.

If there a way to achieve the same result without using switch statement

if(responsecode == 200){
const cfields = ["author", "title", "genre", "price"];

cfields.forEach(myFunction);

function myFunction(item) {
    var reqprop = item;

pm.test("Verify that "+reqprop+" is not empty", function () {
    switch(reqprop) {
  case'author':
  pm.expect(requestObjectprop.author, "Request is successful with a null '"+reqprop+"' ").and.not.be.empty;
    //pm.expect(contentValue).to.be.a('string').and.not.be.empty
    break;
  case 'title':
    pm.expect(requestObjectprop.title, "Request is successful with a null '"+reqprop+"' ").and.not.be.empty;
    break;
}
   
});
}
}

Thank you


Solution

  • It is JavaScript, so you can work with those constructs. For instance, it appears you are testing the response, so I do something like:

    pm.test("Response should be 200", function () { 
        pm.response.to.be.ok;
        pm.response.to.have.status(200);
    });
    
    pm.test("Validate Header for Content-Type", function () {
        pm.expect(pm.response.headers.get('Content-Type')).to.contain('application/json');
    });
    
    pm.test('Should have the result', function () {
        const ResponseText = pm.response.json();
        pm.expect(ResponseText.length).greaterThan(2);
    });
    
    // This is where you have many options. 
    // 1. Simply test the field without a loop
    pm.test("Validate JSON response contains proper data", function () {
        var jsonData = pm.response.json();
        pm.expect(jsonData.author).not.null;
        pm.expect(jsonData.title).not.null;
    
    });
    
    // 2. Loop through the field list as you were doing
    pm.test("Validate JSON response contains proper data", function () {
        var jsonData = pm.response.json();
        // const cfields = ["author", "title", "genre", "price"]; // You can do this, but it is not needed
        ["author", "title", "genre", "price"].forEach((FieldName) => {
            pm.expect(jsonData[FieldName]).not.null;
        });
    });
    
    // 3. If needed, you can also loop through records in a response
    pm.test("Validate JSON response contains proper data", function () {
        var jsonData = pm.response.json();
        jsonData.forEach((OneRecord) => {
            ["author", "title", "genre", "price"].forEach((FieldName) => {
                pm.expect(jsonData[FieldName]).not.null;
            });
        });
    });