Postman While loops and Include Help

Hi All,

Quick question on while loops. I am trying to do it on an include, but JS keeps complaining. Can someone point out the obvious please?

var i = 1;

while (i <=10)

{

    if ((pm.response.json()[i].to.include("Howdy"))

    {

        pm.test("Howdy was found in Page");

    }

i++;

}

When i try to run as a test i am told:

There was an error in evaluating the test script: TypeError: pm.response.text(…)[attemptCount].to.include is not a function

Any help is appreciated.

Hi @JBird20 :wave:

Not entirely sure, but from what I see: the if commands have an extra ( preventing this from compiling. Could you remove the same and see if that helps?

if (pm.response.json()[i].to.include(“Howdy”))

If the issue persists, could you provide us some screenshots or further details on your workflow which would help us identify this better?

Hey,

sorry for the late response.

I have update the loop as you have advised. However, i think the issue i am now having is more to do with the body response type.

In the code i am doing

if (pm.response.json()[i].to.include(“Howdy”))

However, the response body comes back as HTML. Is there a way to do

if (pm.response.html()[i].to.include(“Howdy”))

as when i try i get the following:

JSON:

There was an error in evaluating the test script: JSONError: Unexpected token ‘<’ at 6:1 ^

HTML

There was an error in evaluating the test script: TypeError: pm.response.html is not a function

And this just Locks up Postman

var i = 1;

while (i <=10);

const $ = cheerio.load(pm.response.text());

//output the html for testing

data = $.html();

{

    if (data()[i].to.include("Howdy"))

    {

        pm.test("Howdy was found in Page");

    }

i++;

}

@JBird20, would it be possible for you to share the response the API is returning? Or better yet, is this a public endpoint? It will be easier to assist if we can see the response being returned. I’d also recommend seeing if this particular endpoint can return JSON ( may be documented in the API ).
Regarding the error There was an error in evaluating the test script: JSONError: Unexpected token ‘<’ at 6:1 ^

That’s normal as you’re trying to parse a JSON object, but on a response that isn’t JSON, so it throws an error.

The second error is straightforward; you’re attempting to call the HTML() method on pm.response but that’s not a function. You can take a look at the sandbox here: https://www.postmanlabs.com/postman-collection/Response.html for some of the available methods on the Response. You could try using pm.response.toJSON() and work from there if that helps.

Regarding your loop. It locks up because looking at the code it looks like your loop is the following:
while (i <=10); This condition will always be true, so it’s an infinite loop. It should be:

while(i <=10 ){
// do something
i++;

}

I hope this helps!

2 Likes