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

@allen.helton 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 @dannydainton

1 Like