Callback response in Jest is different than normal response - react-native

I have a method that calls an endpoint in React Native and I want to test it with jest. Everything is asynchronous and it works but the callback response when the function is called in testing side is totally different than the response when the function is called normally in application.
Normally, my response will be a JSON like this:
"_bodyBlob":{
"_data":{
"__collector":[
"Object"
],
"blobId":"43564E12-D797-4971-80C7-A6E06D690F8A",
"name":"login",
"offset":0,
"size":784,
"type":"application/json"
}
},
"_bodyInit":{
"_data":{
"__collector":[
"Object"
],
"blobId":"43564E12-D797-4971-80C7-A6E06D690F8A",
"name":"login",
"offset":0,
"size":784,
"type":"application/json"
}
},
"bodyUsed":false,
"headers":{
"map":{
//a lot of private data here and others
}
},
"ok":true,
"status":200,
"statusText":"",
"type":"default",
"url":"private url"
}
But the response that is returned when called the method by Jest is like this:
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: <Buffer >, disturbed: false, error: null },
[Symbol(Response internals)]: {
url: undefined,
status: 200,
statusText: 'OK',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: undefined
}
}
Which is not even a JSON.
Is this a normal response for a callback when the method is called by Jest or could be something wrong while I call the function because it's all asynchronous?
Thank you for your time.

It seems in your Jest test the response is the javascript Response object: https://developer.mozilla.org/en-US/docs/Web/API/Response
In order to get the JSON out of it, you need to apply its json() method like in this example: https://developer.mozilla.org/en-US/docs/Web/API/Response#an_ajax_call
So once you get the response object, do this:
const jsonValue = await response.json();
The reason why the value is different in jest and in your actual application could be that in your actual application, the library handling the response probably calls the json object before passing you the response.

Related

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

expo camera react native

I am using the expo camera feature to submit scanned images. I have used TakePicutreAsync and have a base64 image. The scan is working fine. But at the time of submitting images, there following is the server error when I try to send a HTTP POST request in try catch block,
Cannot read properties of undefined (reading '1')
and on front end it errors the partial request body (everything minus the features, see below) and that is the error object from which I can make no sense of the error.
I am using formData to form my request as below:
const body = {
frontImg: frontImageBase64,
backImg: backImageBase64
}
var obj1 = {"content": JSON.stringify(body)};
var obj2 = [{"type": "LABEL_DETECTION"}];
formData['image'] = obj1;
formData['features'] = obj2;
Here is the complete request formed ( part of which is spit out as error body from try(POST Request) catch block
FormData {
"_parts": Array [],
"features": Array [
Object {
"type": "LABEL_DETECTION",
},
],
"image": Object {
"content": "{\"frontImage\":\"/9j/4AAQSkZJRgABAQAAAQABAAD/4g...
}
}
What could be going wrong in submitting images or how do I debug with the error message being same as the request body with just image property and not features and nothing else?
Below is the error object body for reference.
error Object {
"config": Object {
"adapter": [Function xhrAdapter],
"data": "{\"_parts\":[],\"image\":{\"content\":\"{\\\"frontImage\\\":\\\"/9j/4AAQSkZAAAAA...

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

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

Crossdomain jQuery ajax request was not called and give error status "parsererror"

I am trying to call cross domain url. which has response text as below.and it is valid json response.
[{"LANG_CODE":"UK_EN","COU_ISO_CODE":"BGR"},
{"LANG_CODE":"UK_EN","COU_ISO_CODE":"HUN"},
{"LANG_CODE":"UK_EN","COU_ISO_CODE":"PRT"},
{"LANG_CODE":"UK_EN","COU_ISO_CODE":"UGA"}]
Jquery ajax code which i am using for calling cross.
$.ajax({
url: "http://someDomainName/restfulservice/Api/Countries/Get_Json",
dataType: 'jsonp',
crossDomain: true,
async: false,
success: function (data) {
alert("success >> "+data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error : "+errorThrown + ", textStatus >> "+textStatus);
}
});
every time it goes to error block. when i inspect this service in browser then it gives response text with valid json string.but through code i am getting error "jQuery18305917718204907095_1409810925309 was not called, status: parsererror".
while this code is working for the url "http://api.geonames.org/findNearbyPlaceNameJSON?lat=47.3&lng=9&username=demo".
what could be the issue for same ?
It is sending back JSON but you have said dataType: 'jsonp'. JSON is not JSONP.
Either change the service to support JSONP or change the client to expect JSON (which might require you to find some other way to circumvent the same origin policy)

Callback not getting called on Internet Explorer for Ajax JSONP call

I'm making an Ajax call using JSONP to fetch JSON data from a third-party (domain different from my site) and its working on Chrome and Firefox but failing on IE (9 & 10 are the versions I have tried). In the IE debugger I see the call is completing (with Http 200) but the callback I've specified for the JSONP call is not being invoked.
My code looks like this:
$.ajax({
url: 'http://api.yipit.com/v1/deals/?key=mykey&division=seattle&limit=1000',
dataType: 'jsonp',
contentType: "text/javascript",
async: false,
cache: false,
crossDomain: true,
jsonp: 'callback',
jsonpCallback: 'processResult',
error: function (xhr, textStatus, error) {
window.alert(error);
},
success: function (data) {
window.alert(JSON.stringify(data));
_yipit_deals = data.response.deals;
}
});
And the response body looks like this:
<html><body><pre>processResult({
... [valid JSON data]
});</pre></body></html>
When the call is made, the error function is getting invoked with error as: Error: processResult was not called and the IE debugger shows a script error caused when trying to parse the <html><body><pre> tags in the response. When running on Chrome and Firefox these html tags don't exist in the response body and I'm not sure why the response is different in the case of IE.
It appears that these tags are causing IE to barf and not be able to invoke the callback. I've tried specifying other values for contentType such as "text/html", "text", "application/javascript" and even not specifying it at all, but its not made any difference. I'm using JSONP to get around the cross-domain issue.
Any ideas? Thanks!
You have to pass an explicit format argument to the URL:
&format=json
Otherwise, it's just pretty-printing the output:
<html><body><pre>{
"meta": {
"code": 401,
"message": "Key not recognized",
"name": "AuthenticationFailed"
},
"response": {}
}</pre></body></html>
Also, I would set async back to true.