How to use a env var in a test to verify the error message format

I am creating a new grid using a post request.
I am storing the name of the grid in the response in an env var as shown below:
const Grd = pm.response.json();
postman.setEnvironmentVariable(ā€œgrid_nameā€, Grd.name);

In my next request I am trying to create a new grid using the same name from the prev request (grid_name)
And I have to write a test to validate the following error message displayed:
ā€œGrid with name ā€˜Grid vy56xl6xy3nā€™ exists.ā€
where ā€˜Grid vy56xl6xy3nā€™ is the grid name from the prev request which is stored in the env var ā€œgrid_nameā€

My test looks like below where the env var doesnā€™t get recognized:

pm.test(ā€˜Verify error message for duplicate nameā€™, ()=>{
pm.expect(Grd.errors[0]).contains(ā€œCommission grid with name {{grid_name}} exists.ā€);
});

I see the following error for my test:
Verify error message for duplicate name | AssertionError: expected ā€˜Grid with name ā€˜Grid vy56xl6xy3nā€™ exists.ā€™ to include ā€˜Grid with name {{grid_name}} exists.ā€™

How should I write my test for this scenario?

To access variables in script sections , you should use

   pm.environment.get ("grid_name")

@praveendvd is right, but Iā€™d recommend reading the documentation to get a better understanding of how variables work in Postman.

Thanks @praveendvd
My question here is how to use that env var while validating the error message in my below test

pm.test(ā€˜Verify error message for duplicate nameā€™, () => {
   pm.expect(Grd.errors[0]).contains(ā€œCommission grid with name {{grid_name}} exists.ā€);
});

I donā€™t think I can use something like below?

pm.test(ā€˜Verify error message for duplicate nameā€™, () => {
 pm.expect(Grd.errors[0]).contains(ā€œCommission grid with name  pm.environment.get ("grid_name") exists.ā€);
});

@allenheltondev Sure! Thanks.

Youā€™d need to do something like this in order to use the variable like that:

pm.test(ā€˜Verify error message for duplicate nameā€™, () => {
 pm.expect(Grd.errors[0]).contains(`Commission grid with name ${pm.environment.get("grid_name")} exists.`);
});

That works. Thanks @danny-dainton

1 Like