How to read the contents of a Post request on Postman? - testing

In the systems I am testing, there are cases that the response informs 200 (ok), but the content may indicate an error in the internal validations of the backend service. How can I read the contents of the response with Postman and schedule a successful validation if this service error code comes as expected?

You can use the tests tab in Postman to run checks on the body (JSON and XML). There are snippets which show you the syntax. You can adapt them to check for the element of the response body which indicates the error.

Postman has a tab called "Tests" where you can provide you test script for execution.
If you want to validate your request responded with 200 OK, following is the script
pm.test("Status test", function () {
pm.response.to.have.status(200);
});
If you want to validate the response contains any specified string,
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});
In your case am assuming the above script can be used. In case the response body is JSON,
pm.test("JSON Body match", function () {
var respBody = pm.response.json();
pm.expect(respBody.<json node>).is.to.equal("Error_name");
});
Example JSON response body
{
"id" : 100,
"status" : "Bad Request"
}
pm.test("JSON Body matches string", function () {
var respBody = pm.response.json();
pm.expect(respBody.status).is.to.equal("Bad Request");
});

Related

Express res.send or res.json doesn't contain a body

I'm calling an API to fetch orders for a given user based on ID which are fetched from a third-party site. These are fetched correctly as a console.log them in the node server. But when I try to send the results back to the client neither res.send nor res.json results sending the data back to the client. Here is an example of an order from console.log:
{"customer":{"orders":{"edges":[{"node":{"id":"gid://shopify/Order/1234564564","lineItems":{"edges":[{"node":{"title":"Some title here"}}]}}}]}}}
Then on the client in the devtools when I console.log the response I get:
body:ReadableStream
locked:false
[[Prototype]]:ReadableStream
bodyUsed:false
headers:
Headers {}
ok:true
redirected:false
status:200
statusText:"OK"
type:"basic"
url:"http://localhost:9000/api/getOrders?cid=gid://shopify/Customer/1234564564"
[[Prototype]]:Response
Any help is appreciated.
=== UPDATE ===
I've now even tried the most basic of examples and am getting the same response on the client:
app.get('/testExpress', (req, res) => {
res.send("Hello")
});
Thanks to #laurent here is how I was able to receive that response on the client:
fetch('/testExpress')
.then(async (r) => {
const resp = await r.text();
console.log(resp);
})
You should try to get the json out of the response by const json = await response.json().
These are the available methods to parse the response body depending on what you want:
Response.arrayBuffer()
Returns a promise that resolves with an ArrayBuffer representation of the response body.
Response.blob()
Returns a promise that resolves with a Blob representation of the response body.
Response.clone()
Creates a clone of a Response object.
Response.formData()
Returns a promise that resolves with a FormData representation of the response body.
Response.json()
Returns a promise that resolves with the result of parsing the response body text as JSON.
Response.text()
Returns a promise that resolves with a text representation of the response body.
https://developer.mozilla.org/en-US/docs/Web/API/Response
The Response object is a representation of the http response. You should try to receive the body of the response by using one of these methods or parsing the body from the readable stream response.body.

Saving a Postman collection variable from he response body

Trying to figure out why I cannot get this to work? Also, console does not give much of a result.
Scenario:
Making the POST request to get the response with TOKEN
Save the response token to collection variable (as the collection file will be used for importing to another testing solution in the cloud)
Using that collection variable to log out from the session
So, I need to be able to store this as a collection variable and use that token when logging out from the session/DELETE the API admin session.
Error in the console:
There was an error in evaluating the test script: JSONError: Unexpected token 'o' at 1:2 [object Object] ^
Tests:
var response = pm.response.json()
var jsonData = JSON.parse(response)
pm.collectionVariables.set("token", jsonData.response.token);
Response body:
{
"response": {
"token": "***"
},
"messages": [
{
"code": "0",
"text": "OK"
}
]
}
Thank you very much for any advice!
JSON.parse(responseBody) always gets a json representation of the response.
A complete fail safe approach would be:
pm.test("response is ok", ()=>{
pm.response.to.have.status(200)
})
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", jsonData.token);
Here's the approach i used.
Send the request
Check if there response is 200
If it's true set the token
pm.test("response is ok", ()=>{
if( pm.response.to.have.status(200)){
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", jsonData.token);
}
})
You need to change your status code depending on the condition.
Hope it helps

How can I mock an http error response in dart?

So I'm doing some unit tests for my http provider.
In one of my tests I want to verify that when I do a POST call and I get an error response with status 409 I do then a call to PATCH and everything works.
This is my code
Future<IdentityResponse> _createUser(dynamic body) {
return http
.post(api, body: json.encode(body))
.catchError((err) {
return _isStatusCode(err, 409) ? _patchUser(body) : throw (err);
});
}
I'm using mockito, and tried first returning a Response like this:
when(http.post(argThat(startsWith(api)), body: anyNamed('body')))
.thenAnswer((_) async => Response("user exists", 409);
And it works... kind of. I catch the error, but then I can't get the status code, I get only the message 'user exists'
If I change to the structure that the backend returns, which is {"error": { "code": 409 }} and I do this:
when(http.post(argThat(startsWith(api)), body: anyNamed('body')))
.thenAnswer((_) async => Response(json.encode(fakeErrorResponse), 409);
Then my catch does not work anymore (??)
I tried then to return an error instead of a response, like this:
when(http.post(argThat(startsWith(api)), body: anyNamed('body')))
.thenAnswer((_) => Future.error(fakeErrorResponse));
Now my catch works again, but the error I get is an _ImmutableMap and I see no easy way to retrieve my data from there.
How can I mock an http error that returns the body that I want and not a simple String?
Thanks

Requesting parameters are not sent over API in ionic 2

I am trying to send the the parameters using a post request but the parameters are not reaching to provide back the desired result and printing null as a result in console. here is my code
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded' );
let options = new RequestOptions({ headers: headers });
let postParams = {
acesscode: 'XXXXXXXXXXX',
productCode:'XXXXXXXXXX'
};
this.http.post("http://www.ebiebook.com/drmapi/v1/details", JSON.stringify(postParams), options)
.subscribe(data => {
console.log(data['_body']);
}, error => {
console.log(error);// Error getting the data
});
}
and the output screen is attached, It shows API is hitting well but the parameters data is unable to reach to provide the corresponding result. Please suggest.
This print you have attached does not show what is being sent by the request, instead it shows only the response your browser received from the server.
You better take a look at this thread here to see in this thread more about. You have to check the 'Headers' tab from Chrome's console -> Network.

Servlet response format for dojo xhrPost error handler

To trigger the error handler for dojo's xhrPost, is there a specific format in which the server response is to be sent? Or just setting the status code to the required error code in the HttpServletResponse object does the work.
Thanks,
RR
You only need to set the appropiate HTTP status code in the HttpServletResponse. I think anything greater than or equal to 400 will be considered an error by the XHR object.
Of course you can also send actual content in your response (via its output stream) and set its content type. You'll receive that in your handler as well:
dojo.xhrPost({
url: '/request',
load: function(data, ioargs) { /* ... */ },
error: function(error, ioargs) {
// error is a Javascript Error() object, but also contains
// some other data filled in by Dojo
var content = error.responseText; // response as text
var status = error.status; // status code
}
});
You can also get responseText and status from ioargs.xhr, which is the full XmlHttpRequest object.