How to know the response of a callback rest call protractor - protractor

I am running an automation script. We have a scenario where Java makes a callback REST call to UI. Below is the code where am doing httpGet to that URL. I want to know when the response comes. If it comes how to know that. I searched a lot I din't find a clear answer anywhere. Please give some hints!
http.get(siteUrl, function(response) {
var bodyString = '';
response.setEncoding('utf8');
response.on("data", function(chunk) {
bodyString += chunk;
});
response.on('end', function() {
defer.fulfill({
statusCode: response.statusCode,
bodyString: bodyString
});
});
}).on('error', function(e) {
defer.reject("Got http.get error: " + e.message);
});
//If we are sure that response has come, then extract it
httpGet("http://testurl").then(function(result) {
//alert('inside test automation');
console.log(result);
});

You can use the response detail whether success or fail with "response code", there are lots of way using interface as callback, using methods by checking response code, lots of network library available - volley, okhttp rest client etc...
help : response code detail
if(response.statusCode == 200) {
// do success work read response etc...
// you can call methods what you want if success happen
} else {
// you can check other status code too..
// call methods if api get fail.
}
Hope this would help
good luck.

Related

Nuxt Axios Module read status code

I'm calling a Rest API that returns at least 2 success status codes .
A normal 200 OK and a 202 Accepted status code.
Both return a Content in the body.
If I execute in postman my calls I might get something like
Status code: 202 Accepted. With Body "Queued" or some other values
or
Status code: 200 OK. With Body "ValueOfSomeToken"
Making the call with axios in my nuxt app:
this.$axios.$get('/Controller/?id=1')
.then((response)=>{
if(response=='Queued'){
//Do something
}
else if (response=='Expired'){
//Do something
}
else{
//Do something
}
})
.catch((error)=>{
console.log(error);
});
..works, but I actually would like to get the status code (because 202 has other values for the body responses)
I have no idea how to read the status codes.
I tried using (response,code) =>... but code is then nothing.
You can use non $-prefixed functions like this.$axios.get() instead of this.$axios.$get() to get the full response
// Normal usage with axios
let { data } = await $axios.get('...'));
// Fetch Style
let data = await $axios.$get('...');
(source)
You can extract the status codes from the response object in axios
if you print the response object (as shown in below image) you can see the all the objects inside the response object. One among them is status object
response.status will give you the status code that is sent from the server
axios.get("http://localhost:3000/testing").then((response)=>{
console.log("response ",response);
if(response.status == 200){
//do something
}
else if(response.status == 202){
//do something
}
else if(response.status == 301){
//do something
}
}).catch((err)=>{
console.log("err11 ",err);
})
In the server side, you can explicitly send any status code using res.status() method, for more details refer this documentation
app.get('/testing',(req, res)=> {
res.status(202).send({"res" : "hi"});
});
Update:
By default, #nuxtjs/axios returns response.data in the .then((response))
The $axios.onResponse event will have access to the complete response object.
You need to setup an interceptor to intercept the $axios.onResponse event and modify the response object
Under plugin directory create a plugin, plugin/axios.js
Update the plugins section plugins : ['~/plugins/axios']
in nuxt.config.js
export default function ({ $axios, redirect }) {
$axios.onResponse(res=>{
console.log("onResponse ", res);
res.data.status = res.status;
return res;
})
}
In the res object in this interceptor you will have the all the values (as it is shown in my first screenshot). But this res object is not returned as it is, only res.data is returned to our program.
We can update contents inside res.data and then return the res object as shown in my program res.data.status = res.status; .
Now when axios returns res.data we will have access to res.data.status value in response object in the .then((response)) promise
You can access the status using response.status inside this.$axios
this.$axios.$get("url").then((response) =>{
console.log("status ",response.status);
}).catch((err) => {
console.log("res err ",err);
});

Getting partial api data from firebase functions- actions-on-google

When I try to access external API's for my google action from my webhook which is hosted on firebase functions, I am getting back only partial content. It stops getting the whole data provided by the api.
For example I tried getting data from wikipedia api using this code
var request = require('request');//required module
//inside the function
request({ method: 'GET',url:'https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&explaintext=&exsectionformat=plain&redirects=&titles=11_September'},function (error, response, body)
{
if (!error && response.statusCode == 200)
{
console.log(body);
}
});
app.ask('data obtained');
Can anyone please help me out with this.
I am having a pay as you go firebase account that allows egress of data.
From just the code fragment, the problem is that you're replying to the user outside the callback from request(). This means that it is handled immediately and the function may end before the entire body has been received. Try something like this (I've also changed ask() to tell() since you're not prompting for another response here, and you shouldn't leave the microphone open.)
var request = require('request');//required module
//inside the function
request({ method: 'GET',url:'https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&explaintext=&exsectionformat=plain&redirects=&titles=11_September'},function (error, response, body)
{
if (!error && response.statusCode == 200)
{
console.log(body);
app.tell('data obtained');
}
});

Asynchronous Request to Facebook API with Redux

I am using Redux and trying to make a call to Facebook API with their JS SDK. I've only ever used promises with Redux and so since the method FB.getLoginStatus just returns a simple JS object, I'm not sure how to ensure that the payload doesn't return undefined.
With redux-promise, you add it to the applyMiddleware(ReduxPromise)... and then it ensures nothing is returned until the promise resolves. But I don't know how to do that here.
I've also used async/await functions with React Native without an issue, but I tried using them here and for some reason the code still returns the payload, before the asynchronous request (await ...) is finished. So I tried working with redux-await, but couldn't get it to work.
export function getLoginStatus() {
var res = FB.getLoginStatus(function(res) {
console.log(res);
});
console.log("res ", res);
return {
type: GET_LOGIN_STATUS,
payload: res
}
}
Hm, things can get a little tricky as I've not used redux-promise. And I can't tell exactly what else you have tried. But this would be my first shot:
async function _getLoginStatus() {
var payload = new Promise( (resolve, fail) => {
FB.getLoginStatus((res)=>resolve(res));
});
return {
type: GET_LOGIN_STATUS,
payload: payload
}
}
// Last time I exported an async function I needed this HYMMV
export let getLoginStatus = _getLoginStatus;
And then elsewhere in the code:
import {getLoginStatus} from 'whatever.js';
var payloadResult = await getLoginStatus();

protractor - testing rest end point

I am trying to invoke rest end point from Protractor E2E tests. I have referred to following site, however this post seems to be based on old API
eg: protractor.promise.defer(); seems no longer valid on latest API.
http://squirrel.pl/blog/2014/01/15/direct-server-http-calls-in-protractor/
Could you please advise/give sample code to invoke rest end point based on latest protractor API (>= 1.3).
I'm trying to write generic function, something like following.
var executeRequest = function(method, url) {
var defer = protractor.promise.defer();
// method can be ‘GET’, ‘POST’ or ‘PUT’
request({uri: url, method: method, json: true}, function(error, response, body) {
if (error || response.statusCode >= 400) {
defer.reject({
error : error,
message : response
});
} else {
defer.fulfill(body);
}
});
// Return a promise so the caller can wait on it for the request to complete
return defer.promise;
};
You could use request-promise instead. Example from their website...
var rp = require('request-promise');
var options = {
uri : 'http://posttestserver.com/post.php',
method : 'POST'
};
rp(options)
.then(console.dir)
.catch(console.error);
I have used npm module - "needle" to invoke restAPI . That has option for redirects, which helped to validate test site even after redirect.
Please find below sample test to validate rest endpoint is up and running.
it("check restendpoint service is running", function(done){
var restendpointUrl = browser.baseUrl + 'service';
needle.get(healthcheckUrl,{follow_max : 5}, function(err,resp) {
expect(resp.statusCode).toBe(200);
if (!err && resp.statusCode == 200) {
expect(true).toBe(true);
} else {
expect(false).toBe(true);
}
done();
});
});
Brine, many thanks for your earlier reply.

How can I send a success status to browser from nodejs/express?

I've written the following piece of code in my nodeJS/Expressjs server:
app.post('/settings', function(req, res){
var myData = {
a: req.param('a')
,b: req.param('b')
,c: req.param('c')
,d: req.param('d')
}
var outputFilename = 'config.json';
fs.writeFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
if(err) {
console.log(err);
} else {
console.log("Config file as been overwriten");
}
});
});
This allows me to get the submitted form data and write it to a JSON file.
This works perfectly. But the client remains in some kind of posting state and eventually times out. So I need to send some kind of success state or success header back to the client.
How should I do this?
Thank you in advance!
Express Update 2015:
Use this instead:
res.sendStatus(200)
This has been deprecated:
res.send(200)
Just wanted to add, that you can send json via the res.json() helper.
res.json({ok:true}); // status 200 is default
res.json(500, {error:"internal server error"}); // status 500
Update 2015:
res.json(status, obj) has been deprecated in favor of res.status(status).json(obj)
res.status(500).json({error: "Internal server error"});
In express 4 you should do:
res.status(200).json({status:"ok"})
instead of the deprecated:
res.json(200,{status:"ok"})
Jup, you need to send an answer back, the simplest would be
res.send(200);
Inside the callback handler of writeFile.
The 200 is a HTTP status code, so you could even vary that in case of failure:
if (err) {
res.send(500);
} else {
res.send(200);
}