Stringify variables into the response test?

Is it possible to add my variables in the pm.test string ?
Say I’m using a post request that would create an account, currently my pm.test is Status Code 201 for example, however I’m trying to make it provide the string information from variables that I’m using to create the account.
For example some of my variables would be inserted in the first and last name for the account, so I also want to make them appear in the pm.test response.

pm.test("{{firstName}} {{lastName}} - ID - {{id} , status code 201.", function () {
    pm.response.to.have.status(201);
});

Hey @theToncheff,
You can use pm.variables.get() to access your variables in the scripts. You can refer https://learning.getpostman.com/docs/postman/environments-and-globals/variables/#accessing-variables-through-scripts for more info.

1 Like

Depending on what you’re doing/trying to do - You could reference the values in a number of ways.

Take them straight from the response data (The structure of your response, might mean you would need to tweak the references):

let firstName = pm.response.json().firstName,
    lastName = pm.response.json().lastName,
    id = pm.response.json().id


pm.test(`${firstName} ${lastName} - ID - ${id} , status code 201.`, function () {
    pm.response.to.have.status(201);
});

Use the pm.variables.get('var_name') function like @bhargavkaranam96 mentioned:

pm.test(`${pm.variables.get('firstName')} ${pm.variables.get('lastName')} - ID - ${pm.variables.get('id')} , status code 201.`, function () {
    pm.response.to.have.status(201);
});

Or even use the .replaceIn function, so that you can use the {{...}} syntax:

pm.test(`${pm.variables.replaceIn('{{firstName}}')} ${pm.variables.replaceIn('{{lastName}}')} - ID - ${pm.variables.replaceIn('{{id}}')} , status code 201.`, function () {
    pm.response.to.have.status(201);
}); 

Many different ways of achieving the same thing and I’m sure there are a few more too :slight_smile:

1 Like

Thanks, I eventually used the variables from the environment with ${pm.environment.get(‘variable’)},
but taking them from the response data is what I was looking for, which also solved another issue for me, as I was trying to get data earlier by responseBody (apparently not how its done) instead of response.json.

So double solutions, thanks again!

1 Like

on a side note, could I make the test to give the variables on different lines

pm.test(`${firstName} ${lastName} - /Newline -
ID - ${id} , status code 201.`, function () {
    pm.response.to.have.status(201);});

The syntax would be \n for a new line but I believe that the names and Assertion Errors in the Test Results tab, are all rendered on a single line until it starts to wrap the text.

I might be wrong though.