Postman test scripts are ignored when inside a try/catch

Hi there community! I have a problem regarding test scripts. Context: i need to collect information about test results and update xray/jira in real time, when a collection is run manually. So i used try/catch in order to update a global variable containing the test result. Here is an example:

pm.globals.set("status", 'PASSED');

pm.test("Check if response contains all the keys", function () {
       try {
     pm.expect(pm.response.json()).to.be.an('object').that.has.all.keys('amount', 'currency')
    
   } catch {
       pm.globals.set("status", 'FAILED')
       };
    });

The problem is Postman reports the test is passed, even tho pm.expect… is false. Has anyone a better idea how to do this and get the correct result? Thanks

Postman uses the Chai assertion library which doesn’t support soft assertions.

As soon as a pm.expect fails within a pm.test block, it will stop executing any more code so it will never hit the catch.

What you can do is use the same pattern that is used for the 15 days of Postman challenges.

What this does is set a counter at the tops of the tests tab to track the passed\failed tests. (Based on how many pm.test blocks you have).

// counter for passed tests
let pass = 0
let totalToPass = 2

Within your test block, you add the following at the bottom after any pm.expect lines. (Which will only execute if all of the assertions passes).

    pass += 1

You can then have an IF statement at the end of your tests tab to check

if (pass == totalToPass) {
     pm.globals.set("status", 'PASSED');
} else {
     pm.globals.set("status", 'FAILED')
}

Thank you for your answer!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.