Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use conditional statement with Postman's new pm.* API?

I have a question about how to use the new pm.* API with conditional statements. Please take a look at the following example code

if(pm.test("Status code is 200", function({
   pm.expect(pm.response.code).to.equal(300);})){
    
   var token = pm.response.headers.get("Authorization");
   pm.environment.set("JWT Token", token.substr(7));
    
   pm.test("Response body is empty ", function () {
      pm.expect(pm.response.text().length).to.equal(0);
   });
}

console.log(pm.test("Status code is 200", function() {pm.expect(pm.response.code).to.equal(300)}));

As I may want to perform certain tests e.g. only when 200 is returned I wanted to use if. However, when I deliberately changed the equal value to 300 just to check if this works, both tests are run and the variable is set, even though the first test fails.

The console.log returns an empty object instead of true/false for the assertion. And if I use something like

console.log(pm.expect(pm.response.code).to.equal(300));

I'll get an error message:

There was an error in evaluating the test script: AssertionError: expected 200 to equal 300

Does anyone know how to solve this?

Cheers

like image 697
Guestz0r Avatar asked Oct 25 '17 10:10

Guestz0r


2 Answers

I have also asked this question on a Postman's github and I've got help. Apparently pm.test does not return the result of the test because you can have multiple assertions in one pm.test and those are executed asynchronously.

Following code works as expected:

pm.test("Status code is 200", function() {
   pm.expect(pm.response.code).to.equal(200);
});
    
(pm.response.code===200 ? pm.test : pm.test.skip)("Response body is empty", function () {
  pm.expect(pm.response.text().length).to.equal(0);
        
  var token = pm.response.headers.get("Authorization");
  pm.environment.set("JWT Token", token.substr(7));
});
like image 164
Guestz0r Avatar answered Oct 30 '22 22:10

Guestz0r


If all you're looking to do here is skip the remaining tests if the response code is something other than 200, you could do the following:

pm.test("Status code is 200", function() {
    pm.expect(pm.response.code).to.equal(200);
});

if (pm.response.code !== 200) {
    return;
}

// Tests that require 200 could continue here
like image 29
scotto Avatar answered Oct 31 '22 00:10

scotto