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;
});