Body matches string fails

Hi there

I do define variables taken from random variables in a pre-request script as following:

pm.collectionVariables.set(“username”, Math.floor(Math.random() * 1000))
pm.collectionVariables.set(“name”,"{{$randomLastName}}");

I use the same variables in my request body:

{
“username”: “user{{username}}”,
“name”: “{{name}}”,
}

And then i test in my test script if i can find the values for {{username}} and {{name}} in the response:

pm.test(“Body matches string”, function () {
pm.expect(pm.response.text()).to.include(“user”,"{{username}}");
});

pm.test(“Body matches string”, function () {
pm.expect(pm.response.text()).to.include("{{name}}");
});

The first test succeds, but the second one fails…i do not see why as the value is correctly generated and also concluded in the response.

The console says:

Body matches string | AssertionError: expected ‘{“name":“Stehr”,“prename”:“Nathaniel”,“username”:“user239”,“organisationalUnit”:“ABC-DEF-GHI”,“telephone”:“0581234567”,“email”:"Haleigh61@gmail.com”,“lang”:“DE”}’ to include ‘{{name}}’

Seems like the variable {{name}} is not loaded correctly?

Does anyone know of this problem?

Greetings and thanks for your help!

Benjamin

In Test tab you cannot use format like {{name}}
you need to fetch variable and save it in JavaScript form

 pm.test("ABC visible in response", function() {
      const Name= pm.collectionVariables.get("name")
      pm.expect(pm.response.text()).to.include(Name) ;
    });

EDIT:
Additional info about using .include assertions
The first parameter is the value that you are searching for. The second one is msg wchich is optional in case of error so in test like

You are searching for “user” only. Not value of variable {{username}}

Here are the official docs https://www.chaijs.com/api/bdd/#method_include

You can access the variable using the {{..}} syntax in the sandbox by using:

pm.collectionVariables.replaceIn('{{name}}') 
1 Like

As this dynamic variables also require additional line I like to stick with assigning it to named JS variable :wink:
But this is just my habit

1 Like

Wasn’t pushing to use a certain method :grin: just responding to this :grin:

In Test tab you cannot use format like {{name}}

1 Like