Search code examples
javascriptpostman-testcase

True / false written on console , trying to write tests in postman. If false, fail the test


I have contains function that prints in console as true/ false, I need to write a tests in postman so that if found false, fail the tests and can be shown on tests tab. In the below const testfalse= gives the value true or false in console. But if found false, I need to have a tests to fail if fund false. I have tried with if condition, which is not logging anything

    // Getting the category name and name key
var categname= pm.environment.get("categoryName");
console.log(categname)
var categnamekey= pm.environment.get("categorynameKey")
console.log(categnamekey)

var arr=JSON.parse(responseBody); 
function contains(arr, key, val) {
    for (var i = 0; i < arr.length; i++) {
        if(arr[i][key] === val) 
        return true;
    }
    return false;
}

// To verify if value present or not which prints true or false

const testfalse=console.log(contains(arr, "name", categname)); 
console.log(contains(arr,"nameKey",categnamekey));

if(testfalse=='false'){
    tests["fail"]
}else {
    tests["success"]
}

Solution

  • You can use pm.expect(someValue).to.equal(expectedValue) method to compare if the value is what you expected. If it's not the same, the failed test will show in the result.

    Also your testFalse should just be the check, you can console.log at any time, it won't affect the test... it will just give you a log to review when the test runs.

    const testfalse = contains(arr, "name", categname);
    console.log('Category found: ' + testfalse); 
    
     //rest of code here
    
    //Test will either pass or fail after this line and reflect on test tab
    pm.expect(testfalse).to.equal(true); //maybe rename testPass
    

    https://learning.postman.com/docs/postman/scripts/test-scripts/