ReferenceError when setting a Global variable in Postman - 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

Related

Cannot set global variable in postman script

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

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 - How can I compare a message using vars

can anyone help me, I am almost new in Postman.
my issue is as follow:
I send a POST request and get a message asresponse:
{
"errorCode": 1000,
"errorDescription": "Account is not verified by Admin!"
}
this message is already saved in a var named "messageAccountIsnotVerified"
when I try to use comparison in postman tets script and compare the message with the expected string is working fine:
pm.test("test", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.errorCode).to.eql(1000);
pm.expect(jsonData.errorDescription).to.eql("Account is not verified by Admin!");
});
But When I try to save the String text "Account is not verified by Admin!" in a variable named: messageAccountIsnotVerified
and try to make the same comparison
pm.test("test", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.errorCode).to.eql(1000);
pm.expect(jsonData.errorDescription).to.eql("messageAccountIsnotVerified");
});
or
pm.test("test", function () {
var jsonData = pm.response.json();
var message = pm.environment.get("messageAccountIsnotVerified");
pm.expect(jsonData.errorCode).to.eql(1000);
pm.expect(jsonData.errorDescription).to.eql(message);
});
it failed with error:
test | AssertionError: expected 'Account is not verified by Admin!' to deeply equal 'messageAccountIsnotVerified'
Can someone explain to me
1. what does the "deeply equal" mean and
2. what do I wrong and
3. how can I use the assertion by using the variable
Thanks for any Hint
Just additional Info: I have the same issue when I compare email with
# sign in another message - so I assume may be something to do with special chars
You need to get the variable in the following way:
pm.expect(jsonData.errorDescription).to.deep.equal(pm.environment.get("messageAccountIsnotVerified"))
.to.deep.equal can be used to reference something further down in a nested object.
Add .deep earlier in the chain to use deep equality instead. See the deep-eql project page for info on the deep equality algorithm: https://github.com/chaijs/deep-eql.
Looking at the response body you posted { "errorCode": 1000, "errorDescription": "Account is not verified by Admin!" }, I don't see a problem with the first test but for it to complain about deep equal then this response is probably no exactly as you posted.
You could reduce this all down again if you wanted too:
pm.test("test", () => {
pm.expect(pm.response.json()).to.deep.equal({"errorCode": 1000, "errorDescription": "Account is not verified by Admin!"})
});
That test would do the same as above.
let string = pm.response.json()
pm.expect(string).to.equal("String from Response")

Hypen in response data is throwing error when setting as global variable

I have a post man request. Which returns a response data as:
{
"app-token": "VcdQeqG1aJYrlNH40VuRfjyedQEC"
}
I need to extract the value of the app-token and set as global variable.
here is my code:
var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("token", jsonData.app-token);
But I am getting error. Can some one help me.
You should use bracket notation for properties that contain hyphens or other operators instead of dot notation.
Because compiler will interpret jsonData.app-token as a subtraction operation like jsonData.app - token
Use this one instead:
postman.setGlobalVariable("token", jsonData["app-token"]);
the best and i suppose only one solution is to write parameter inside square brackets and inverted commas at the same time.
f.e.
var responseBody = JSON.parse(responseBody);
pm.globals.set("variable_key", responseBody['app-token']);