Postman - How can I compare a message using vars - postman

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")

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

Postman validation, Getting AssertionError: VAR: expected 'createdTime' to deeply equal 'VAR'

I'm trying to verify the value created as part of the response, value is the same found in the global variable set in previous request within same collection.
Anything you can advise or try?
Tests:
pm.test("Created Time is present", function () {
pm.expect("createdTime", pm.response.json().createdTime).to.be.eql(pm.globals.get("createdTime"));
});
Response:
Created Time is present | AssertionError: 2020-03-31T20:07:15Z:
expected 'createdTime' to deeply equal '2020-03-31T20:07:15Z'
Correct assertion in your case is:
pm.test("Created Time is present", function () {
pm.expect(jsonData.createdTime).to.eql(pm.variables.get("createdTime"));
});

Trying to get two postman.setNextRequest (not chained) or two Actions in Workspace

I’m quite new to postman (and coding) and was trying to find and piece together many snippets of scripts to make it work the way I want.
What I want is very simple: I have a list of IDs that I want to make a POST in each of them, get one of the responseBody as a variable and do another POST. I think I’m close but I can’t manage to get it to work.
I’ve tried:
Two POST request in the same Collection and running the collection.
In the first request I have a POST to
https://APIADDRESS/?order_id{{orderid}}&contract[copy_order_data]=true
On the Pre-request Script tab:
var orderids = pm.environment.get(“orderids”);
if (!orderids) {
orderids = [“bc46bf79-2846-44ed-ac4d-78c77c92ccc8”,“81aacc33-1ade-41a3-b23e-06b03b526b8f”];
}
var currentOrderId = orderids.shift();
pm.environment.set(“orderid”, currentOrderId);
pm.environment.set(“orderids”, orderids);
On the Tests tab:
var orderids = pm.environment.get(“orderids”);
if (orderids && orderids.length > 0) {
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable(“invoice.id”, jsonData.invoice.id);
postman.setNextRequest(“Create invoice”);
} else {
postman.setNextRequest(null);
}
invoice.id is a environment variable populated with the response body of the first action/post and then using the variable on the second action/post.
And then the second request would be a POST to
https://APIADDRESS/invoices/{{invoice.id}}/finalize.json
Of course this doesn’t work. Either it doesn't run the second request in the collection or it doesn't do the loope to more than 1 ID on the list.
So I thought that putting the second POST inside the first one would solve it. But I had no luck.
Can please someone help me?
I have tried mentioned use case with sample API's provided by POSTMAN.
Can you try it?
First POST Method Request : https://postman-echo.com/post
Pre-request Script of first POST method
var orderids = pm.environment.get("orderids");
if(!orderids ){
orderids = ["bc46bf79-2846-44ed-ac4d-78c77c92ccc8","81aacc33-1ade-41a3-b23e-06b03b526b8f"];
}
var currentOrderId = orderids.shift();
pm.environment.set("orderid", currentOrderId);
pm.environment.set("orderids", orderids);
Tests Tab of first POST Method
var orderids = pm.environment.get("orderids");
if (orderids && orderids.length > 0) {
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("invoice.id", jsonData.headers.host);
postman.setNextRequest("Test1");
} else {
postman.setNextRequest(null);
}
Second POST Method Reqeust: https://postman-echo.com/post?key={{invoice.id}}
After executing the above collection it will set orederids and invoice.id value in environment variables and then it will call next POST Method.
Hope this will help you.
Thanks #HalfBloodPrince, from the Postman Echo it worked but in my case it doesn't :S
What I manage to get it working was using a Json file as a list of Orderids.
In that case I've separated all requests.
Request1 - https://APIADDRESS/?order_id{{orderid}}&contract[copy_order_data]=true
Tests tab:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("invoice.id", jsonData.invoice.id);
Request2 - https://APIADDRESS/invoices/{{invoice.id}}/finalize.json
That way everything is in a neat and organized way.
Thanks

How to build a Postman url query with Pre-request Scripts

I'm trying to use a pre-request script to build out a request object based on data pulled from a CSV file. The problem is that the request seems to be set in stone prior to the pre-request script being run. That would seem to make this a mid-request script almost rather than a pre-request.
My code is as follows:
if(ipList === undefined) ipList = "1.2.3.4,2.3.4.5,123.234.345.465";
let ips = ipList.split(',');
let queryArray = [];
for( i=0; i<ips.length; i++){
queryArray.push({ "key": "ip", "value": ips[i] });
}
console.log(queryArray);
pm.request.url.query = queryArray;
console.log(pm.request);
When I hardcode a url query variable in the request to equal 4.3.2.1, the pm.response.url object like this:
pm.request.url.query[0] = {key:"ip", value:"4.3.2.1"}
Note that the url.query[0] part of the object matches the parameter in the actual get request.
When I change the value of pm.request.url.query to equal the new query array, however as you can see here, the query array is set correctly, but the parameters are not appended to the request URL.
So unless I'm doing something wrong, it appears that the request is immutable even to the pre-request scripts.
So my question is this:
Is there a way to modify the url params of a request prior to making the request?
BTW: I know that is might seem odd to have multiple params with the same key in a query, but that's the way this API works and hard coding multiple ip addresses in the query works just fine.
You could just assign a new value to pm.request.url.
Here I had some query params already in the URL, which I had to edit:
const urlSplit = request.url.split('?');
const paramsString = urlSplit[1]; // the second part actually represents the query string we need to modify
const eachParamArray = paramsString.split('&');
let params = {};
eachParamArray.forEach((param) => {
const key = param.split('=')[0];
const value = param.split('=')[1];
Object.assign(params, {[key]: value});
});
params.bla = params.bla + 'foobar';
newQueryString = Object.keys(params).map(key => key + '=' + params[key]).join('&');
pm.request.url = urlSplit[0] + '?' + newQueryString;
In the end, I just constructed a new URL, using the first part of the previous one & the query string with the edited bla parameter.
This seemed to work for me--it didn't change what the UI shows the query string is, but it changed what the actual request was (looking at the console log)
pm.request.url.addQueryParams(["a=1", "b=2"])
pm.request.url.query.remove("b")
I have some parameters called "script_loginAs" etc... named such that people on my team know the parameter is evaluated and not sent.

Twitter Typeahead remote

I am trying to use Twitter typeahead but I am facing a problem. I don't know how typeahead passes the string to the server. Is it through a GET parameter? If so, what is the name of the parameter?
Easiest through a GET parameter, you can choose whatever parameter you want.
In JS:
$('#search').typeahead({
name: 'Search',
remote: '/search.php?query=%QUERY' // you can change anything but %QUERY, it's Typeahead default for the string to pass to backend
});
In PHP (or whatever backend you have):
$query = $_GET['query'];
Hope you get the basic idea.
You might want to consider something like this, it is a very basic remote datasource example. The get parameter in this example is 'q'
// Get your data source
var dataSource = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: 'path/to/your/url/json/datasource/?q=%QUERYSTRING',
wildcard: '%QUERYSTRING'
}
});
// initialize your element
var $typehead = $('#form input').typeahead(null, {
source: dataSource
});
// fire a select event, what you want once a user has selected an item
$typehead.on('typeahead:select', function(obj, datum, name) {
//your code here
});
////////////////////////////////////
# in python (django) we get a query string using the request object passed through a view like this
query = request.GET.get('q') or ""
//the caveat [or ""] is just to prevent null exceptions
///////////////////////////////////
# using php
$query = ($_GET['q']) ? $_GET['q'] : "";