If statement failing: always adding collection variable even though test has failed

Hi,

I have the following JSON response

[

    {

        "nid": "387",

        "changed": "1612429358"

    },

    {

        "nid": "388",

        "changed": "1612439271"

    },

    {

        "nid": "389",

        "changed": "1612958700"

    },

    {

        "nid": "399",

        "changed": "1613139731"

    },

    {

        "nid": "392",

        "changed": "1613140500"

    },

    {

        "nid": "393",

        "changed": "1613145772"

    }
]

And I’m running the following test to verify that a specified ‘nid’ is returned in the response.

/* Verify apprenticeship in the status of "Published" is correctly returned */

    var resp = JSON.parse(responseBody);

    var _ = require('lodash')

    var apprenticeshipexists = _.find(resp, function(o) { 

           return o.nid == pm.collectionVariables.get("publishedNID"); });

    pm.test("Published apprenticeship is returned", function () {

        pm.expect((apprenticeshipexists) != null).to.be.true});

    //If test has passed add apprenticeship ID as a variable for use in further tests

    if (pm.expect((apprenticeshipexists) != null).to.be.true = true){

        pm.collectionVariables.set("PublishedIDTemp", pm.collectionVariables.get("publishedNID"));

    } else

        {console.log("Test failed apprenticeship ID not present");

        }

The test is ‘passing’ and ‘failing’ correctly, however my if statement is always adding the variable '“PublishedIDTemp” even when pm.expect((apprenticeshipexists) != null).to.be.true returns as false. Can you help?

Thanks

In my opinion, this code is hard to follow because you’re mixing assertions in your if statements. I’d rewrite it for maintainability sake to something like the following:

const publishedNID = pm.collectionVariables.get('publishedNID');
const jsonData = pm.response.json();
const apprenticeship = jsonData.find(data => data.nid === publishedNID);

pm.test('Published apprenticeship is returned', function(){
  pm.expect(apprenticeship).to.not.be.undefined;
});

if(apprenticeship) {
    pm.collectionVariables.set('PublishedIDTemp', publishedNID);
}
else {
  pm.collectionVariables.unset('PublishedIDTemp');
}

If an assertion fails in a test, it will stop executing code from that point on in the specific test. This means if you want to do some things based on the existence of that object, you’d need to move the logic outside of the assertion.

One thing I noticed is that you weren’t explicitly unsetting the PublishedIDTemp variable, which might have led to some of your confusion.

Let me know if this helps!

Hi @allen.helton, many thanks that worked perfectly.

1 Like