Test if response Body include any of values

My question:
I want to create a test that will search if the response body contains any of a certain set of strings.

Details (like screenshots):
The built in snippet: “Response Body: Contains string” allows only one string to be verified
pm.test(“Body matches string”, function () {

pm.expect(pm.response.text()).to.include("string_you_want_to_search");

});

How I found the problem:

I’ve already tried:
I tried to loop over an array with the built in function, but it did not work

pm.test(“Testing multiple values”, function () {

var arr = [“string A”, “string B”, “string C”],

responseText = pm.response.text();

arr.forEach((x) => {

if (pm.expect(responseText).to.include(x)){

result = true;

return result;

}

});

});

1 Like

@praveendvd @KKKK1947
Thanks but it is not quite what I looked for.
I need to verify that ANY item in the response list is equal to ANY of the requested values.
If only one of the items in the list equals one of the requested values, the test pass.
The issue you mentioned validates that EACH item in the list is equal to ANY of the requested values.

Please give an example, would try to help you out ,:hugs:

Here’s a fixed version of the script that you were trying. Your main problem is that you were using a pm.assert to check each value in turn, which means that it fails as soon as it hits any string which isn’t present. What you’d need to do in this example is just use a Javascript check to set your boolean, and then do a pm.assert on your boolean at the end. Like this:

pm.test("Testing multiple values", function () {

    result = false;
    var arr = ["string A", "string B", "string C"];
    responseText = pm.response.text();

    arr.forEach((x) => {
      if (responseText.includes(x)){
      result = true;
    }

    pm.expect(result).to.be.true;
    });
});

However, I think what you’re actually trying to find is a way to do this natively without having to write your own code. The good news is, there is one! Try this: (note that for testing purposes, I changed the responseText to a string so that I could check if the assertion was working)

pm.test("Testing multiple - simple", function () {
    var arr = ["string A", "string B", "string C"];
    responseText = "I have string D inside me";
    pm.expect(responseText).to.contain.oneOf(arr);
});

This correctly fails in this example, because the response doesn’t contain string A, B or C:

…but it passes if the response contains one (or more) of the strings.

1 Like

I think this was resolved here: Assert contains multiple strings - #5 by sivcan