Cannot set global variable in postman script - postman

When I log in to a Fortinet device via API, It returns a variable called fpc-sid. This is their version of an authtoken.
When I attempt to put this on a global variable on the test section in the login request it returns the fpc-sid and then I get:
"ReferenceError: sid is not defined"
For some reason, I think it doesn't like the "-", but not sure.
How can I set fps-sid as a global variable?
var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("fpc-sid", jsonData.fpc-sid);

var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("fpc-sid", jsonData.fpc-sid);
Property cannot be accessed like that when it is not a valid identifier. use it by name as :
var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("fpc-sid", jsonData['fpc-sid']);
Read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
Also use the pm object pm.globals.set() for setting variable as Danny mentioned. This is the new syntax, this will make it more future proof

Related

ReferenceError when setting a Global variable in Postman

I get an error when trying to extract a value from a JSON response body in Postman.
ReferenceError: teste is not defined
This is what I have tried:
var jsonData = JSON.parse(responseBody);
pm.globals.set("access_token",jsonData.access_token)
** pm.globals.set("x-teste-msg-sign",jsonData.x-teste-msg-sign)
It's more than likely to be this, judging by the way you're extracting the access_token
pm.globals.set("x-teste-msg-sign", jsonData["x-teste-msg-sign"])
As the key contains the - character, you would need to use bracket notion rather than dot notion to access the value.
Here's an example:
let jsonData = {
"x-teste-msg-sign": 12345
}
console.log(jsonData.x-teste-msg-sign) // This would cause a script error
console.log(jsonData["x-teste-msg-sign"]) // This would set the value to the variable

How to extract the values from the response body in postman

After posting the request, API return response body as string
Response body look like
{ UniqueID = 93243434,birthGender = M,birthDate = 11/1/2018 5:51:18
PM, familyNames = James, givenNames = Test }
when I try to set the environment variable using the below code
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("currentUniqueId", data.UniqueId);
I got the below error on test results
Error message:
There was an error in evaluating the test script: JSONError:
Unexpected token 'U' at 1:3 { UniqueID = 93243434,birthGender =
M,birthDate = 11/1/2018 5:51:18 PM, family ^
my goal is I need to extract the value 93243434 and assign to environment variable.
Hi you are using the correct way but you can try this version
var jsonData = pm.response.json();
pm.environment.set("UNIQUE_ID", jsonData.UniqueID);
The set("UNIQUE_ID" will help you save it in variable and you can name it as you want and jsonData.uniqueID will extract what you want to get from the Json response
If you view my approach I am extracting Access code and company id and saving it in variable and calling it in all next api's
You are using a notation pattern that is deprecated.
Instead of set your variable using:
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("currentUniqueId", data.UniqueId);
Try to set your variable this way:
pm.environment.set('currentUniqueId', pm.response.json().UniqueID);
To get more information, try: https://learning.getpostman.com/docs/postman/scripts/test_examples/

Postman - How to store multiple values from a response header in a var or just be able to see them

Using a GET in postman with the URL posted below, I am able to store the entire response header in question with all of its data in a var, the issue for me is how do I verify the pieces of data inside that var
here is my URL
http://localhost/v1/accounts?pageNumber=1&pageSize=2
[
using postman I am able to get the above in a var
var XPaginationData = postman.getResponseHeader(pm.globals.get("PaginationHeader"));
pm.globals.set("XPaginationData", XPaginationData);
is there a way to get the individual values inside the response header X-Pagination stored in a different var to assert later
using this in postman
pm.globals.set("XPaginationData", JSON.stringify(pm.response.headers));
console.log(JSON.parse(pm.globals.get('XPaginationData')));
console.log(JSON.parse(pm.globals.get('XPaginationData'))[4].value);
I get
how would i go about getting "TotalCount" for example
BIG EDIT:
thanks to a coworker, the solution is this
//Filtering Response Headers to get PaginationHeader
var filteredHeaders = pm.response.headers.all()
.filter(headerObj => {
return headerObj.key == pm.globals.get("PaginationHeader");
});
// JSON parse the string of the requested response header
// from var filteredHeaders
var paginationObj = filteredHeaders[0].value;
paginationObj = JSON.parse(paginationObj);
//Stores global variable for nextpageURL
var nextPageURL = paginationObj.NextPageLink;
postman.setGlobalVariable("nextPageURL", nextPageURL);
You could use JSON.stringfy() when saving the environment variable and then use JSON.parse() to access the different properties or property that you need.
If you set a global variable for the response headers like this:
pm.globals.set('PaginationHeader', JSON.stringify(pm.response.headers))
Then you can get any of the data from the variable like this:
console.log(JSON.parse(pm.globals.get('PaginationHeader'))[1].value)
The image shows how this works in Postman. The ordering of the headers returned in the console is inconsistent so you will need to find the correct one to extract data from the X-Pagination header
Looks like an issue with Postman itself.
The only solution that worked for me was to stringify & parse the JSON again, like this:
var response = JSON.parse(JSON.stringify(res))
After doing this, the headers and all other properties are accessible as expected.

Postman - Can you use the {{...}} syntax within a Test script?

I have an environment variable called "url", the value is a combination of several other variables in the same environment.
Here is the bulk environment variable definition:
scheme:http
server:localhost
port::55881
application:/
url:{{scheme}}://{{server}}{{port}}{{application}}
As you can see, url contains other variables.
This works great in the actual request (I'm using {{url}} when addressing my service), but when I try to use the same variable in my scripted tests (In the Tests tab), I'm getting the un-evaluated version.
var serviceUrl = pm.variables.get("url");
console.log(serviceUrl); //Yields {{scheme}}://{{server}}{{port}}{{application}}
Is there a way to get the evaluated value inside my tests?
Thanks!
Complete test for more insight:
var jsonData = JSON.parse(responseBody);
tests["Status code is 200"] = responseCode.code === 200;
var ordrereferanse = jsonData.Ordrereferanse;
tests.OrdreReferanse = ordrereferanse.length > 0;
//Have to do this
var scheme = pm.variables.get("scheme");
var server = pm.variables.get("server");
var port = pm.variables.get("port");
var application = pm.variables.get("application");
var api_key = pm.variables.get("api_key");
var serviceUrl = scheme + "://" + server + port + application;
//Instead of this - an environment variable defined like this "{{scheme}}://{{server}}{{port}}{{application}}"
//var serviceUrl = pm.variables.get("url");
//remaining test - go to url to verify that the resource is created and the order reference is set
var infoUrl = serviceUrl + "ordreinformasjon/" + ordrereferanse + "?format=json&api_key=" + api_key;
pm.sendRequest(infoUrl, function (err, response) {
var info = response.json();
console.log(info);
tests.OrdreInformasjonOrdreReferanse = info.OrdreReferanse === ordrereferanse;
});
This would work but I'm not sure what you're trying to achieve:
var scheme = pm.variables.get("scheme")
var server = pm.variables.get("server")
var port = pm.variables.get("port")
var application = pm.variables.get("application")
console.log(`${scheme}://${server}${port}${application}`)
That would log out http://localhost:55881/ to the console.
The {{...}} syntax doesn't work in the way that you had it in the environment file. As it's just storing everything as a string so that's why you would get that output.
You could use {{scheme}}://{{server}}{{port}}{{application}} as the URL but not in the tests using the same syntax.
UPDATE
After seeing the update to the question - Could you not combine the separate variables into a single url variable and construct the infoUrl variable in the following way:
var infoUrl = `${pm.variables.get("url")}ordreinformasjon/${ordrereferanse}?format=json&api_key=${pm.variables.get("api_key")}`
Then use a different environment file with the same url key but with a different value if you need to point the request at a staging or production URL.
I've also noticed that you're using the older tests syntax rather than the newer pm.test() syntax, that might clean up some of the code for you.

Remove text qualifier when copying to variable in postman

I have an issue using a text variable from a response body and inserting into a request without the text qualifiers.
I'm trying this:
var data = JSON.parse(responseBody);
postman.setGlobalVariable("basketid", responseBody);
This is the response
"14b5f921-78d9-4ab2-a5a0-828f00fcf63a"
When I look at the basketid variable the text qualifiers are still there which mean that when I call
{{url}}/api/{{basketid}}
I get an error.
Do anyone know of a way to save the variable without text qualifier?
The following worked for me:
var _token = responseBody.slice(1,-1);
pm.globals.set("token", _token);
If you are getting "14b5f921-78d9-4ab2-a5a0-828f00fcf63a" as it is in global environment as you said, you can use eval:
var jsonObj = JSON.stringify(responseBody);
var setObj=eval("("+jsonObj+")");
postman.setGlobalVariable("basketid",setObj);
I ran into the same issue today while trying to store my token and this is what worked for me:
var data = JSON.parse(responseBody);
postman.setGlobalVariable("token", data.token);