Search code examples
javascriptpostmanjavascript-objectspostman-pre-request-script

How to pass global variables to JSON object for validation in Javascript


Hello I am now to javascript and writing script for API testing in Postman to automate my usecases. Need help for below query.

Lets say i have my API request as below.

API request: https://reqres.in/api/users/2

Response:

{
   "data":{
      "id":2,
      "email":"[email protected]",
      "first_name":"Janet",
      "last_name":"Weaver",
      "avatar":"https://reqres.in/img/faces/2-image.jpg"
   },
   "support":{
      "url":"https://reqres.in/#support-heading",
      "text":"To keep ReqRes free, contributions towards server costs are appreciated!"
   }
}

Query is from the response if the data.id == 2 then i have to read the 'email' & 'avatar' keys from global variables of postman and start the validation.

Code:

const response = JSON.parse(responseBody);
if (response.data.id === 2) {
//Here i have to read the 'email' & 'avatar' keys from global variables of postman.
tried response.data.pm.globals.get('email') & response.data.pm.globals.get('avatar') but its failing as the calling itself is not proper i belive.
}

Please help and thanks in advance.


Solution

  • Use this code in Tests section

    const response = JSON.parse(responseBody);
    
    if (response.data.id === 2) {
        pm.globals.set("email", response.data.email);
        pm.globals.set("avatar", response.data.avatar);
        console.log(pm.globals.get("email"))
        console.log(pm.globals.get("avatar"))
    }
    

    You can see it's result at console.

    enter image description here