Assert contains multiple strings

How to assert that variable contains multiple strings?

Something like
pm.expect(myText).to.include("text1", "text2");

Is there a ready-made solution without looping?

@e.mikhailov Since postman uses a fork of chai plugin for assertions, the library doesn’t support this feature.

Without looping over an array it won’t be possible.

Code snippet could be something like this:

let expectedStrings = ['text1', 'text2'];

expectedStrings.forEach((s) => pm.expect(responseString).to.have.string(s));
2 Likes

Thanks a lot, your solution seems compact too

1 Like

Hi @singhsivcan .
I tried your snippet but I need something a little different:

pm.test(“Verify any of the following strings”, function () {

let expectedStrings = [‘1110’, ‘1119’];
responseText = pm.response.text();
expectedStrings.forEach((s) => pm.expect(responseText).to.have.string(s));

});

but I need a relation of ANY of the expected strings, not AND (Meaning, if any of the expected is found , the test Pass)

Can you please help?

I think it can be quickly done using Array.some and a little tweaking of the test case:

pm.test("Verify any of the following strings", function () {
  let expectedStrings = ["1110", "1119"];
  responseText = pm.response.text();

  const hasAnyExpectedString = expectedStrings.some((s) => responseText.includes(s));
  pm.expect(hasAnyExpectedString).to.be.true;
});

Thanks! works perfectly!

1 Like

Hi @singhsivcan .
Can you help me with verifying also ANY OF given strings in ANY OF selected field value of an array?
eaxmple:
Verify that 1234 or 4567 equals the value of any “check_code” field below:

{
“id”: “0”,
“checks”: [
{
“check_number”: 1,
“check_code”: 1234
},
{
“check_number”: 2,
“check_code”: 5678
}
]
}

I think you can simply map over the items and find the intersection. An optimized way would be to loop and bail-out, but that’s something you can try yourself also.

I’ve not tested the following code, but something like this should do the job in a “compact” (looking) way:

const _ = require('lodash');
pm.test("Verify any of the following strings", function () {
  let expectedCodes = [1234, 5678],
   codes = _.map(pm.response.json().checks, 'check_code');

  pm.expect(_.intersection(codes, expectedCodes)).to.not.be.empty;
});