How to use dynamic environmental variable in another test?

Hi, I am new to Postman
In 1st Post request, I’ve created a Reward and got an id

Response Body:
{
“id”: 2138,
“label”: “Some New Test Reward”,
“description”: “Some new test description”,
“disclaimers”: “Some new test disclaimer message.”,
}

In Tests I wrote a script:

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable(“rewardId”, jsonData.id);

Now I have it as a dynamic environmental variable

In the 2nd Get request, I am getting a list of rewards and I want to make sure a new reward is created and assert it by that id using the dynamic environmental variable

Response Body:
“_embedded”: {
“rewards”: [
{
“id”: 1762,
“label”: “Sample Reward”,
“description”: “”,
“disclaimers”: “Not to be used in combination with other deals.”,
},
{
“id”: 2093,
“label”: “Some edited label (deleteme)”,
“description”: “Some edited description”,
“disclaimers”: “Not to be used in combination with other deals.”,
},
{
“id”: 2138,
“label”: “Some New Test Reward”,
“description”: “Some new test description”,
“disclaimers”: “Some new test disclaimer message.”,
}
]
}

I was able to assert that reward by its label, here is my code:

pm.test(“Verify if created reward label exists in the rewards list”, function () {

var jsonData = pm.response.json(); 

var labelRewardIndex = jsonData._embedded.rewards.map(
        function(filter) {
            return filter.label;
        }
    ).indexOf("Some New Test Reward"); 

var rewardFilter = jsonData._embedded.rewards[labelRewardIndex];

pm.expect(rewardFilter.label).to.include("Some New Test Reward")

});

Maybe there were better ways to do that. How can I or should I reuse that code to assert “Some New Test Reward” by “id”: 2138, using a dynamic environmental variable that I created in the previous request?

Thanks in advance

Hi @igorg.zelenov

If you wanted to run it as a test you could use something like;

const response = pm.response.json();

pm.test("Is created", function () {
    for (let x = 0; x < response._embedded.rewards.length; x++) 
    {
        try
        {
            //You could set the 2138 value to be a variable from previous request
            pm.expect(response._embedded.rewards[x].id).to.eql(2138);
        }
        catch(e)
        {
            pm.test("Is not created", () => {throw new Error(e)});
        }
    }
});

Or if you wanted to output to the console only, you could try something like;

const response = pm.response.json();

for (let x = 0; x < response._embedded.rewards.length; x++) 
{
    if (response._embedded.rewards[x].id === 2138)
    {
        console.log("IS CREATED");
    }
}