If statement in Postman tests

Gene Truuts picture Gene Truuts · Aug 8, 2018 · Viewed 18.2k times · Source

I work in Postman and I want to build the test construction like that:

var login_status = pm.environment.get("LOGIN_STATUS");
var jsonData = pm.response.json();
pm.test("TESTS", function () {
    if (login_status === 1) {
        pm.expect...(test 1);
    }else if (login_status === 2) {
                pm.expect...(test 2);
    }else if (login_status === 3) {
                pm.expect...(test 3);

but it doesn't work for me as I want.

In my logic, Postman should check the login status and use only one pm.expect... accordingly to login_status value.

How can I use the if statement in Postman? Thank you!

Answer

Danny Dainton picture Danny Dainton · Aug 8, 2018

The comparison operator you are using is returning false as it's checking for the same type, try using == rather than ===.

The values stored in the Postman environment file is a string and you're doing a strict equal against a number, in the test.

You could also try changing the number value to a string value like this login_status === "1" or use strict inequality so the type you use doesn't matter, like this login_status !== 2.

You could even just use a parseInt() function when you get the value from the file.

parseInt(pm.environment.get("LOGIN_STATUS"))

It's completely up to you and the way you want to construct the check.

More information about the comparison operator can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Identity