Assert the existence of an xml element with cheerio and chai

Hello,

I am using Postman to test a SOAP API. In the tests I use the cheerio library to assert the contents of the xml response. So far it has been easy to use cheerio. I can assert that an element has certain text content or that an element has a certain attribute. For example, the test below works just fine.

pm.test("Response status is 'ok'", function () {
        pm.expect($("response > status").text()).to.eq("ok");
    });

But for some strange reason I haven´t been able to assert that an element exists or not.

The API I am testing is expected to return a report given the right inputs. With wrong inputs an 200 response is still sent, but there is no report element

When I researched I found this SO post: How to check whether the element exist using chai? - Stack Overflow which explains that chai-jquery library is needed to assert DOM elements.

Being very hopeful I tried testing anyway using to.exist but I ended up with a test that always passes even if I point to nonexciting elements.

pm.test("This ought to fail, but it doesn't", function() {
    pm.expect($("response > NonsenseReport")).to.exist; 
});

With cheerio and chai I am already able to traverse the XML document nicely, but yet asserting that a element exists is strangely tricky. I also prefer not to pull in another library in Postman. The contents of the report can change from time to tome so I don’t want to rely on asserting a text content or attribute within the report either. Any ideas how I can easily assert that an xml element exists in Postman?

pm.test("This ought to fail, but it doesn't", function() {
    pm.expect($("response > NonsenseReport").length).to.eql(0); 
});

you could use length property

1 Like

Thanks @praveendvd. Using the length property worked great.

Since I want to assert that the report is created, I ended up asserting that the length is not equal to 0. Something like this:

pm.test("ExpectedReport is generated", function() {
    pm.expect($("response > ExpectedReport").length).to.not.equal(0);
});

Thanks again!

1 Like