TypeError: Cannot read property 'then' of undefined in protractor-cucumber - protractor

I am using cucumber 3 with protractor 5.2.2. and i have given the url in my config file as baseUrl: 'https://www.linkedin.com' and i have to check whether navigated to the home page after clicking login.Instead of passing URL "https://www.linkedin.com/feed" ,i have pass "feed" and given split method in my step.js file.
my feature file is given below
When I enter "qwerty" in ".username"
And I enter "Passw0rd" in ".password"
And I click on ".login"
Then I should be at the "feed"
and in my step.js
Then(/^I should be at the "(.*)"$/, function (url) {
var geturl=browser.getCurrentUrl() + '';
var res=geturl.split("/");
var result=res[1];
return expect(result).to.eventually.equal(url);
});
My fourth step failed and getting error "TypeError: Cannot read property 'then' of undefined".where i am going wrong in my step.js file.Or how can i check the remaining part of base url when i am on inner page which having a url format of "base.com/feed/profile/profile-edit".Thanks in advance.

Explain your code issue inline at below.
Then(/^I should be at the "(.*)"$/, function (url) {
var geturl=browser.getCurrentUrl() + '';
// browser.getCurrentUrl() return a pomise which it's also a javascript object
// in javascript claculate `an object + ''`, will convert the object
// to string firstly by toString() function,
// if the object not overwrite the supper toString() function,
// it will return an string "[object Object]"
// So geturl = "[object Object]"
var res=geturl.split("/");
// there is no "/" in geturl, so the array length of res is 1
var result=res[1];
// res[1] exceed array length, so result = undefined
return expect(result).to.eventually.equal(url);
// because you used eventually at here, so chai will regard result is a promise,
// chai will check the argument of expect(xxx) is a promise or not
// by detect xxx has property: then via calling xxx.then in chai's inside code,
// but result is undefined, of course has no property: 'then'.
});
You have to consume promise eventual value in then()
Then(/^I should be at the "(.*)"$/, function (url) {
return browser.getCurrentUrl().then(function(cururl){
var parts = cururl.split("/");
return expect(parts[parts.length-1]).to.equal(url);
// dont't use eventually at here, because parts[parts.length-1] is not promise
});
});

Related

SAPUI5: getModel returns undefined if called within the same function of setModel

I'm trying to set a model and retrieving it from OData after pressing a certain button.
The problem is when I call getModel right after setting the model, it returns undefined.
However, if I call getModel from another function (after model being stetted from other functions), it returns the desired output.
Code for reference:
onPressButton1: function(){
var vEntityURL = "/CustomerSet(ID='000')";
var sServiceUrl = "/Customers_SRV/";
var oServiceModel = new sap.ui.model.odata.ODataModel(sServiceUrl, true);
var oJsonModel = new sap.ui.model.json.JSONModel();
oServiceModel.read(vEntityURL, {
success: function(oData) {
oJsonModel.setData(oData);
}
});
this.getView().setModel(oJsonModel, "Customers");
var oCustomer = this.getView().getModel("Customers");
console.log(oCustomer.getProperty("/Name"));
}
The above returns undefined in the console.
However, it works if I press another button with the following function.
onPressButton2: function(){
var oCustomer = this.getView().getModel("Customers");
console.log(oCustomer.getProperty("/Name"));
}
This is not a sapui5 problem, it is the common behaviour of asynchronous code: you can be sure to have your data only in the success callback of the read method.
Move the last three lines of code inside the success function and you're done :-)

How to pass a key field as variable instead of hard-coded key value to OData operation?

I am calling the GetEntity OData read method from the SAP UI5 view controller and passing a key value in the request URL. I am getting the proper response from the back-end when I hardcode the key value.
However, when I try to pass the key value dynamically in a variable by appending it to the URL, it doesn't work. I get the following error
HTTP request failed 404
In below code, sGrant is the variable and it doesn't work. But if I replace the variable name with its value hard-coded in below code, for example, in the read method like this: "/GrantMasterSet('TY560003')", then it works:
var sGrant = this.byId("grantNbr").getValue();
var oMod = this.getOwnerComponent().getModel();
oMod.read("/GrantMasterSet('sGrant')", {
success: function(oData) {
var oJsonModel = new JSONModel();
oJsonModel.setData(oData);
this.getView().setModel(oJsonModel);
}.bind(this),
error: function(oError) {
MessageToast.show("Read Failed");
}
});
UI5 has a method to generate the right URI for you, no matter what is the data type of the key of your entity type.
The method is createKey of the sap.ui.model.odata.v2.ODataModel class. See its documentation
Inside your controller, use the following source code.
onInit: function () {
var oRouter = this.getOwnerComponent().getRouter();
oRouter.getRoute("routeName").attachPatternMatched( this.onPatternMatched , this );
},
onPatternMatched: function(oEvent){
var oParameters = oEvent.getParameters();
var oArguments = oParameters.arguments; // is not a function - without ()
var sKey = oArguments.id; // route parameter passed when using navTo
var oDataModel = this.getView().getModel(); // v2.ODataModel
oDataModel.metadataLoaded().then(function() {
var sPath = oDataModel.createKey("EntitySet", { Key: sKey });
this.getView().bindElement("/" + sPath);
}.bind(this)
);
}
Usually this is necessary in details pages, in order to apply element binding to a page. As the createKey method relies on the $metadata of your service, you must make sure that it is already loaded in your app. This can be achieved by using method metadataLoaded, provided in the snippet as well.
You should concatenate the variable to the rest of the string, like this:
oMod.read("/GrantMasterSet('" + sGrant + "')", {
Or, you can use a template literal, which comes down to the same thing (notice the backtics):
oMod.read(`/GrantMasterSet('${sGrant}')`, {
You should escape 'sGrant' so it can be evaluated.
It should be something like that :
var sGrant = this.byId("grantNbr").getValue();
var oMod = this.getOwnerComponent().getModel();
oMod.read("/GrantMasterSet("+sGrant+")", {
success: function(oData) {
var oJsonModel = new sap.ui.model.json.JSONModel();
oJsonModel.setData(oData);
this.getView().setModel(oJsonModel);
}.bind(this),
error: function(oError) {
MessageToast.show("Read Failed");
}
});

actions on google--unable to use app.tell to give response from JSON

I am trying to get my webhook to return a parsed JSON response from an API. I can log it on the console, but when I try to use app.tell; it gives me: TypeError: Cannot read property 'tell' of undefined. I am basically able to successfully get the data from the API, but I'm not able to use it in a response for some reason. Thanks for the help!
[Actions.API_TRY] () {
var request = http.get(url2, function (response) {
// data is streamed in chunks from the server
// so we have to handle the "data" event
var buffer = "",
data,
route;
response.on("data", function (chunk) {
buffer += chunk;
});
response.on("end", function (err) {
// finished transferring data
// dump the raw data
console.log(buffer);
console.log("\n");
data = JSON.parse(buffer);
route = data.routes[0];
// extract the distance and time
console.log("Walking Distance: " + route.legs[0].distance.text);
console.log("Time: " + route.legs[0].duration.text);
this.app.tell(route.legs[0].distance.text);
});
});
}
This looks to me to be more of a JavaScript scoping issue than anything else. The error message is telling you that app is undefined. Often in Actions, you find code like yours embedded in a function which is defined inside the intent handler which is passed the instance of your Actions app (SDK or Dialog Flow).

GWT JSNI returning string from JSNI function

EDIT I think because it is an asychronous call that when I call the method data has not been set yet.
String theData = getData("trainer") // not set yet
I have the following JSNI function. The if I call this function it returns an empty string, however the console.log before it show that data is there. Seems data cannot be returned for some reason.
public native String getData(String trainerName)/*-{
var self = this;
$wnd.$.get( "http://testdastuff.dev/trainerstats", { trainer: trainerName} )
.fail(function() {
$wnd.console.log("error");
})
.done(function( data ) {
console.log("DATA IS: " + data);
return data;
});
}-*/;
Your thought that it is a asynchronous call is correct.
The return of the callback passed to done is not returned to the original call you made.
If you used the following code, you'll get 2 messages in the console, in the first you'll get empty data, and in the second, the correct data.
String theData = getData("trainer");
consoleLog("The data is " + theData);
// suppose consoleLog as a native function to console.log
Thus you should probably do your callback like this.
.done(function( data ) {
console.log("DATA IS: " + data);
theData = data; // if theData is within the same scope and you want to store
doSomethingWith(theData); // <-- here you can interact with theData
})
The doSomethingWith(theData) could even be an invocation to a Java method.

Why when I click on the update button error TypeError: r is undefined happen?

The error in firefox browser as follows: TypeError: r is undefined
This is the chrome browser:
Uncaught TypeError: Cannot read property 'data' of undefined
I also did a video for a better understanding.
The error occurs when I changed the values ​​in a field
jsfiddle code
youtube video
button code update
save: function (e) {
var that = this;
$.ajax({
url: '/api/apdevice',
type: e.model.id == null ? 'POST' : 'PUT',
contentType: 'application/json',
data: JSON.stringify(e.model),
success: function (data) {
alert('yes');
that.refresh();
},
error: function (data) {
alert('no');
that.cancelRow();
}
});
}
The reason for this is because your datasource's update method is being called. It has not been set which gives you the TypeError.
You can do one of two things.
Set the update method of your datasource to contain the logic contained in your save function. You'll need to set update as a function in order to be able to control the method dynamically (POST/PUT). You should remove the ajax code from the save event at this point.
Set the update method to a dummy function and handle it as part of the save event instead.
Here's an example of approach #2.
var dataSource = new kendo.data.DataSource({
..
update: function(e) { return true; }
..
});
Keep the save event function as is.
Note that I'm getting an Uncaught SyntaxError: Unexpected number error. I believe this is originating from the LastClientsCount property.
Fiddle: http://jsfiddle.net/mSRUe/23/