Invalid or unexpected token when referencing #odata.count - postman

I am currently working with an Odata endpoint and am having an issue referencing JSON values with tags including #. The console shows “SyntaxError | Invalid or unexpected token”
JSON Response Body
pm.test("Your test name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.#odata.count).to.eql(73);
});
Can someone explain how I reference that value?

pm.test("Your test name", function() {
var jsonData = pm.response.json();
pm.expect(jsonData['#odata.count']).to.eql(73);
});

Related

Postman test script - how to call an api twice to simulate 409 error

I am trying to run a few automated testing using the Postman tool. For regular scenarios, I understand how to write pre-test and test scripts. What I do not know (and trying to understand) is, how to write scripts for checking 409 error (let us call it duplicate resource check).
I want to run a create resource api like below, then run it again and ensure that the 2nd invocation really returns 409 error.
POST /myservice/books
Is there a way to run the same api twice and check the return value for 2nd invocation. If yes, how do I do that. One crude way of achieving this could be to create a dependency between two tests, where the first one creates a resource, and the second one uses the same payload once again to create the same resource. I am looking for a single test to do an end-to-end testing.
Postman doesn't really provide a standard way, but is still flexible. I realized that we have to write javascript code in the pre-request tab, to do our own http request (using sendRequest method) and store the resulting data into env vars for use by the main api call.
Here is a sample:
var phone = pm.variables.replaceIn("{{$randomPhoneNumber}}");
console.log("phone:", phone)
var baseURL = pm.variables.replaceIn("{{ROG_SERVER}}:{{ROG_PORT}}{{ROG_BASE_URL}}")
var usersURL = pm.variables.replaceIn("{{ROG_SERVICE}}/users")
var otpURL = `${baseURL}/${phone}/_otp_x`
// Payload for partner creation
const payload = {
"name": pm.variables.replaceIn("{{username}}"),
"phone":phone,
"password": pm.variables.replaceIn("{{$randomPassword}}"),
}
console.log("user payload:", payload)
function getOTP (a, callback) {
// Get an OTP
pm.sendRequest(otpURL, function(err, response) {
if (err) throw err
var jsonDaata = response.json()
pm.expect(jsonDaata).to.haveOwnProperty('otp')
pm.environment.set("otp", jsonDaata.otp)
pm.environment.set("phone", phone);
pm.environment.set("username", "{{$randomUserName}}")
if (callback) callback(jsonDaata.otp)
})
}
// Get an OTP
getOTP("a", otp => {
console.log("OTP received:", otp)
payload.partnerRef = pm.variables.replaceIn("{{$randomPassword}}")
payload.otp = otp
//create a partner user with the otp.
let reqOpts = {
url: usersURL,
method: 'POST',
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify(payload)
}
pm.sendRequest(reqOpts, (err, response) => {
console.log("response?", response)
pm.expect(response).to.have.property('code', 201)
})
// Get a new OTP for the main request to be executed.
getOTP()
})
I did it in my test block. Create your normal request as you would send it, then in your tests, validate the original works, and then you can send the second command and validate the response.
You can also use the pre and post scripting to do something similar, or have one test after the other in the file (they run sequentially) to do the same testing.
For instance, I sent an API call here to create records. As I need the Key_ to delete them, I can make a call to GET /foo at my API
pm.test("Response should be 200", function () {
pm.response.to.be.ok;
pm.response.to.have.status(200);
});
pm.test("Parse Key_ values and send DELETE from original request response", function () {
var jsonData = JSON.parse(responseBody);
jsonData.forEach(function (TimeEntryRecord) {
console.log(TimeEntryRecord.Key_);
const DeleteURL = pm.variables.get('APIHost') + '/bar/' + TimeEntryRecord.Key_;
pm.sendRequest({
url: DeleteURL,
method: 'DELETE',
header: { 'Content-Type': 'application/json' },
body: { TimeEntryRecord }
}, function (err, res) {
console.log("Sent Delete: " + DeleteURL );
});
});
});

Can't set variable value to script in Postman

There are two tests in the request, I want to use a different value of the variable in the second request, I set it using the command
pm.variables.set("confirm_emal", "vodani6277#ulforex.com");
Can't set variable value separately for second script
pm.test("Confirmed email", () =>{
//parse the response JSON and test three properties
const responseJson = pm.response.json();
pm.expect(responseJson.email).to.eql('gekisa9678#exoacre.com');
pm.expect(responseJson.auth_key).to.be.eql('557UmPdC2pGV_tA67bSjHGPbtbRz90Hk');
pm.expect(responseJson.first_name).to.eql('Vitalijj');
pm.expect(responseJson.last_name).to.eql('Agarev');
pm.expect(responseJson.birthday_date).to.eql(978307200);
pm.expect(responseJson.register_type).to.eql('email');
pm.expect(responseJson.email_confirmed).to.eql("true");
});
pm.test("unconfirmed email", () =>{
pm.variables.set("confirm_emal", "vodani6277#ulforex.com");
const responseJson = pm.response.json();
pm.expect(responseJson.email).to.eql('vodani6277#ulforex.com');
pm.expect(responseJson.register_type).to.eql('email');
pm.expect(responseJson.email_confirmed).to.eql(false);
});
I get an error that the expected value does not match the response from the server
AssertionError: expected 'vodani6277#ulforex.com' to deeply equal 'gekisa9678#exoacre.com'
What i am doing wrong?

Postman Test with comparison to global variable

I want to orchestrate two requests in Postman. The first response will give me a variable. I save this id to a global variable id. In Postman this variable is usually accessible via {{id}}.
Then I send a second request with this id (like GET foo.bar/{{id}}). Now I want to check, if the id is in the result as well.
This is what I tried in the test code:
var jsonData = pm.response.json();
pm.expect(jsonData.id).to.eql({{id}});
where idis the variable from the first response (e.g. 72b302bf297a228a75730123efef7c41).
The response for the second request looks sth. like this:
{
"id": "72b302bf297a228a75730123efef7c41"
}
Here some examples which did not work either:
var jsonData = pm.response.json();
pm.expect(jsonData.id).to.eql("{{id}}");
var jsonData = pm.response.json();
var myId = {{id}};
pm.expect(jsonData.id).to.eql(myId);
My excpectation is, that the test will be positive and the `id from the request will be found in the response.
Do you have an idea how to solve this problem?
Thanks for the help.
The {{...}} syntax cannot be used like that, in the sandbox environment, you would need to access it this way.
pm.expect(jsonData.id).to.eql(pm.globals.get('id'))
The test syntax would be:
pm.test("IDs equal?", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.id).to.eql(pm.globals.get('id'))
});

Export CSV of a particular request in Postman using Newman

I have a JSON Collection of Postman requests. I am running it via Newman.
Is there a way I can export the XML Response of a particular request(Not all) to a file using newman or postman
Thanks
As I know, there is no developed XML reporter for newman.
The easiest and none-blood way to quickly resolve it this is to add response parsing to certain request or to a collection (if you need for all)
In tests you can add:
let responseJSON = JSON.parse(responseBody)
tests["Status code is 200"] = responseCode.code === 200;
if(responseCode.code !== 200)
{
console.log(responseJSON);
return;
}
OR
try {
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("jwt_token", jsonData.data.token);
} catch (err) {
console.log(err);
}
OR if you don't need to output it only after an error, then put just:
var body = JSON.parse(responseBody)
console.log(body);

Parse Cloud Code with facebook API not working properly

I want to get a location Id from facebook API (that is already in my DB) and than use this to get the events from that location.
So, i'm first running a query to get this info and than adding this result as a parameter in my url. The fact is that the query is returning the result properly but when calling the httpRequest this is failling. Its important to say that my httpRequest works when I use the locationId hard coded.
I guess this problem is occuring because of the response calls but i cant figure out how to fix it. I'm also looking on a better way to design this code. Any ideas?
Parse.Cloud.define("hello", function(request, response) {
var query = new Parse.Query("Location");
query.find({
success: function(results) {
locationId = results[0].get("locationFbId");
console.log(locationId);
},
error: function() {
response.error("Failed on getting locationId");
}
});
Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/v2.2/'+locationId+'/events?access_token='+accessToken,
success: function(httpResponse) {
console.log(httpResponse.data);
response.success("result");
},
error:function(httpResponse){
console.error(httpResponse.message);
response.error("Failed to get events");
}
});
});
Adolfosrs, your problem here is that your two requests are running asynchronously on different threads. Therefore, your first request isn't returning until after your second request has been called. I would suggest chaining the requests as below so that your second request will be initialized with the data retrieved from the first request.
Parse.Cloud.define("hello", function(request, response) {
var query = new Parse.Query("Location");
query.find({
success: function(results) {
locationId = results[0].get("locationFbId");
console.log(locationId);
Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/v2.2/'+locationId+'/events?access_token='+accessToken,
success: function(httpResponse) {
console.log(httpResponse.data);
response.success("result");
},
error:function(httpResponse){
console.error(httpResponse.message);
response.error("Failed to get events");
}
});
},
error: function() {
response.error("Failed on getting locationId");
}
});
});