Is there a way to resolve multiple promises with Protractor? - protractor

I have this:
element(by.id('x')).sendKeys('xxx').then(function(text) {
element(by.id('y')).sendKeys('yyy').then(function(text) {
element(by.id('z')).sendKeys('zzz').then(function(text) {
expect(element(by.id('myButton')).isEnabled()).toBe(true);
})
});
});
The button 'myButton' is enabled when the elements 'x', 'y' and 'z' all have values. It's my understanding that sendKeys returns a promise.
So is this the only way that I can check if 'myButton' which depends on data in all the three fields is enabled?

You don't need to chain any promises because protractor will wait until all the statements are done: https://github.com/angular/protractor/blob/master/docs/control-flow.md
element(by.id('x')).sendKeys('xxx');
element(by.id('y')).sendKeys('yyy');
element(by.id('z')).sendKeys('zzz');
expect(element(by.id('myButton'));
If you want to resolve multiple promises use:
var webdriver = require('selenium-webdriver');
webdriver.promise.fullyResolved(promises);
For example: https://github.com/angular/protractor/blob/d15d35a82a5a2/lib/protractor.js#L327

this is a bit after the fact, but:
var x = element(by.id('x')).sendKeys('xxx');
var y = element(by.id('y')).sendKeys('yyy');
var z = element(by.id('z')).sendKeys('zzz');
myFun(x,y,z).then(function(){
expect(element(by.id('myButton')).isEnabled()).toBe(true);
});
// in a common function library
function myFun(Xel,Yel,Zel) {
return protractor.promise.all([Xel,Yel,Zel]).then(function(results){
var xText = results[0];
var yText = results[1];
var zText = results[2];
});
}
but an even better way:
var x = element(by.id('x')).sendKeys('xxx');
var y = element(by.id('y')).sendKeys('yyy');
var z = element(by.id('z')).sendKeys('zzz');
myFun(x,y,z);
//isEnabled() is contained in the expect() function, so it'll wait for
// myFun() promise to be fulfilled
expect(element(by.id('myButton')).isEnabled()).toBe(true);
// in a common function library
function myFun(Xel,Yel,Zel) {
return protractor.promise.all([Xel,Yel,Zel]).then(function(results){
var xText = results[0];
var yText = results[1];
var zText = results[2];
});
}
another way is to chain the .thens together:
element(by.id('x')).sendKeys('xxx').
then(function(xtext){
element(by.id('y')).sendKeys('yyy');
}).then(function(ytext){
element(by.id('z')).sendKeys('zzz');
}).then(function(ztext){
expect(element(by.id('myButton')).isEnabled()).toBe(true);
});

it seems protractor supports all - protractor.promise.all
read more at:
https://github.com/angular/protractor/issues/2062#issuecomment-94030055
describe('promise.all', function() {
it('should greet the named user', function() {
browser.get('http://juliemr.github.io/protractor-demo');
$('div').click().then(function () {
return protractor.promise.all([
$('h3').getText(),
$('h4').getText()
]);
}).then(function (params) {
console.log('A');
});
});
it('does something else', function() {
console.log('B');
});
If you want to return an object instead of a list, seems you can also do that - used it and it's awesome
element.all(by.css('.fc-event-inner')).map(function(el) {
return {
time: el.findElement(by.className('fc-event-time')).getText(),
title: el.findElement(by.className('fc-event-title')).getText()
}
});
See the properties are actually promises.. protractor will resolve them.

Related

SAPUI5 oData POST 500 error

I'm trying to do a oData create on checkbox pressed and getting the following errors. Not sure if this is front end or a back end ABAP issue as have got this same function working in another project.
It is failing on the create part but strangely is still passing through the details for SiteId, ArticleNumber, VarianceDate & Confirmed.
// Set CheckBox status, X for true, blank for false
onVarianceChecked: function (oEvent) {
var oEntry = {};
var bindingContext = oEvent.getSource().getBindingContext(this.MODEL_VIEW);
var path = bindingContext.getPath();
var object = bindingContext.getModel("SI").getProperty(path);
// Pass in the Header fields
oEntry.SiteId = this.SiteId;
oEntry.ArticleNumber = object.ArticleNumber;
oEntry.VarianceDate = moment(new Date(object.VarianceDate)).format('YYYY-MM-DDTHH:mm:ss');
// Set X or blank
if (oEvent.getParameter("selected") === true) {
oEntry.Confirmed = "X";
} else {
oEntry.Confirmed = "";
}
// Do the create
var oModel = this.getView().getModel("SI");
oModel.create("/VarianceHeaderSet", oEntry, {
success: function () {
console.log("Variance confirmed");
MessageToast.show("Variance confirmed", {
duration: 1000
});
},
error: function (oError) {
console.log("Error, variance could not be confirmed");
MessageToast.show("Error, variance could not be confirmed", {
duration: 1000
});
}
});
}
'000000000' is the initial value for Edm.DateTime, hence it will fail when you have modelled a DateTime property to not be nullable.
Go to SEGW and change the property to "nullable" or make sure that you always provide a correct Date in the POST.

how to put verification in pageobject model in protractor

I have a code (credit to #kishanpatel) Traverse-through-each-row-for-a-column-text which will verify whether the value is added in grid or not. i want to put this in my page object. i was thinking to add the elements into page object and the if condition in a different helper file similar to selenium but i am not sure is that the right appraoch. see the details below.
if I call the mo.helper in spec.ts, it says gridcheck.ispresent() is not a function. How to handle this scenario?
code:
it('verify the grid that master obligation is added', function () {
var testvar = "'test_protractor'";
var row_check = element(by.xpath("//div[contains(text()," + testvar + ")]"));
if (row_check.isPresent()) {
row_check.getText().then(function (msg) {
if (row_check.isPresent()) {
console.log("Grid contains========== " + msg);
}
});
}
});
i have the below method in mo.ts(page object page):
this.grid = function (value) {
// var testvar = "'test_protractor'";
var row_check = element(by.xpath("//div[contains(text()," + value + ")]"));
return require('./mohelper.ts')
}
}
mohelper.ts:
require('../page/mo.ts')
var mohelper = function () {
this.gridvaluepresent = function () {
require('../page/mo.ts')
var gridcheck = mo.grid();
if(gridcheck.isPresent()) {
gridcheck.getText().then(function (msg) {
if (gridcheck.isPresent()) {
console.log("Grid contains========== " + msg);
}
})
}
}
}
module.exports = new mohelper();
spec.ts:
it('go to corresponding module and verify whether the master obligation is added ', function () {
browser.sleep(10000);
taxhome.selectmodule;
taxhome.selectmoduledropdown(1);
mo.grid("test_protractor");
mohelper.gridvaluepresent();
});
Couple of things here to be considered -
1) Most of the protractor's api methods are asynchronous i.e. they return promises you have to resolve/reject them to perform actions.
isPresent() also returns a promise, you need to resolve it-
var row_check = element(by.xpath("//div[contains(text()," + value + ")]"));
row_check.isPresent().then(function(present) {
if(present) { // it returns a boolean value
row_check.getText().then(function (msg) {
console.log("Grid contains========== " + msg);
});
}
});
2) Since you are using TypeScript , use its syntax rather than conventional js-
let row_check = element(by.xpath("//div[contains(text()," + value + ")]")); // Block scoped variable using 'let'
row_check.isPresent().then((present) => { // notice the thick arrow
if(present) {
row_check.getText().then((msg) => {
console.log("Grid contains========== " + msg);
});
}
});
3) Maintain Page Objects efficiently and readable-
All the helper methods, elements etc. for a single page should go in a single page object. Write them in separate classes, typescript uses the concept of classes and transpiles them to global functions.
moHelper.ts
import {ElementFinder, element} from 'protractor';
export class MoHelper {
public row_check: ElementFinder; // its of element finder type
gridValueCheck(value : string) {
row_check = element(by.xpath("//div[contains(text()," + value + ")]")); // please use Css selectors instead of Xpath!
row_check.isPresent().then((present) => {
if(present) {
row_check.getText().then((msg) => {
return msg; // here you are returning the msg of the row from your page!
});
}
});
}
}
Your spec.ts should validate that row msg!
import {MoHelper} from './moHelper.ts'
let mo: MoHelper = new MoHelper();
it('go to corresponding module and verify whether the master obligation is added ', () => {
browser.sleep(10000); // please refrain from using sleeps instead use Expected Conditions
taxhome.selectmodule;
taxhome.selectmoduledropdown(1);
expect(mo.gridValueCheck("test_protractor")).toEqual("Your Expected Message");
});
Please find the links for your reference to understand the above in more detail-
isPresent
Getting started with typescript
Using page objects in protractor/style guide
Expected Conditions

global mongodb cursor in Meteor App

I'm trying to build an app with Meteor and I'm new to the framework.
What I want to do is have the Mongocursor that get returned in the tablets functions with the search parameter to be used in colors functions. Currently in colors I'm just getting the reactive variable again and running the Tablets.find(). But I'm going to have many other functions like this so I want to use the same Mongo cursor. Is it possible to create a global Mongo cursor from the tablets functions that will also be reactive.
The code below is my setup:
Template.tabletsList.helpers({
tablets: function() {
// read the user's last search (if any)
var query = Template.instance().query.get();
// sort options
var options = {sort: {manufacturer: 1}};
if ($.isEmptyObject(query)) {
// if the user didn't input a search just find all tablets
var tabletCursor = Tablets.find({}, options);
return tabletCursor;
}
else {
// find all tablets matching the search expression
return Tablets.find(query, options);
}
},
colors: function() {
var query = Template.instance().query.get();
if ($.isEmptyObject(query))
var allTablets = Tablets.find().fetch();
else
var allTablets = Tablets.find(query).fetch();
var color = '';
var colors = [];
allTablets.forEach(function (tablet) {
for (var i=0; i<tablet.specs.color.length; i++) {
color = tablet.specs.color[i];
if ($.inArray(color, colors) === -1) {
colors.push(color);
}
}
});
return colors.sort();
}
You can create a global helper:
Template.registerHelper('tablets',function(query){
var options = {sort: {manufacturer: 1}};
if ($.isEmptyObject(query)) query = {};
return = Tablets.find(query, options);
});
Then from anywhere in your code you can access this with:
var tabletCursor = UI._globalHelpers.tablets(query);
If you don't have access to query everwhere you can add it to Session or create a new reactive variable to hold it.

Assign mongo selectors in find() dynamically

I have the following problem: I have an interface where a user can filter stuff out based on several inputs. There are 5 inputs. When an input is filled out I want to add it's value to the helper returning the collection. The problem I can't solve is how to do this dynamically. Sometimes the user might fill out one input, sometimes three, sometimes all 5. Within the find() method you can only write down meteor's syntax:
mongoSelector: fieldName,
This means you can only hardcode stuff within find(). But just adding all 5 selectors doesn't work, since if one of the values is empty, the find searches for an empty string instead of nothing.
I thought of doing conditionals or variables but both don't work within find because of the required syntax. What could I do to solve this?
var visitorName;
var visitorAge;
Session.set('visitorName', visitorName);
Session.set('visitorAge', visitorAgee);
Template.web.helpers({
visitors: function() {
return Visitors.find({ visitor_name: Session.get('visitorName'), visitor_age: Session.get('visitorAge') });
}
});
Template.web.events({
"change #visitor_name": function (event, template) {
visitorName = $(event.currentTarget).val();
}
});
Template.web.events({
"click #reset_filter": function (event, template) {
return Visitors.find();
$(input).val('');
}
});
http://jsfiddle.net/m5qxoh3b/
This one works
Template.web.helpers({
visitors: function() {
var query = {};
var visitorName = (Session.get('visitorName') || "").trim();
if (visitorName) {
query["visitor_name"] = visitorName;
}
//same thing for other fields
return Visitors.find(query);
}
});
Template.web.events({
"change #visitor_name": function (event, template) {
var visitorName = $(event.currentTarget).val();
Session.set('visitorName', visitorName);
}
});

How to globally add a custom locator to Protractor?

I wrote a custom locator for Protractor that finds anchor elements by their ui-sref value. In my specs I just used by.addLocator to add the custom locator, but I figured this might be a cool thing to publish and have other people use it.
The goal is to add this custom locator to the global Protractor object so it can be used in any of your specs.
My initial approach was to add this functionality in the onPrepare block of the Protractor config. Something like the pseudocode below:
onPrepare: function () {
require('ui-sref-locator')(protractor); // The protractor object is available here.
}
That require statement would just execute this function:
function (ptorInstance) {
ptorInstance.by.addLocator('uiSref', function (toState, opt_parentElement) {
var using = opt_parentElement || document;
var possibleAnchors = using.querySelectorAll('a[ui-sref="' + toState +'"]');
var result = undefined;
if (possibleAnchors.length === 0) {
result = null;
} else if (possibleAnchors.length === 1) {
result = possibleAnchors[0];
} else {
result = possibleAnchors;
}
return result;
});
};
The problem is that by is not defined on the protractor object available in the onPrepare block. This means that I cannot use the .addLocator method.
Try the following:
function () {
by.addLocator('uiSref', function (toState, opt_parentElement) {
...
By should be in the global scope.
The protractor object passed to the onPrepare block has a By property. That By property has an inherited enumerable property named addLocator. My understanding of JavaScript is pretty shallow so it really threw me off that when I console.log'ed the protractor.By it returned {}, but if I did for (var propName in protractor.By) it would show me all the "hidden" properties. I'm still struggling to understand that bit.
Working code:
onPrepare: function () {
require('ui-sref-locator')(protractor); // The protractor object is available here.
}
The require would execute the function below:
function (ptor) {
ptor.By.addLocator('linkUiSref', function (toState, opt_parentElement) {
var using = opt_parentElement || document;
var possibleAnchors = using.querySelectorAll('a[ui-sref="' + toState +'"]');
var result = undefined;
if (possibleAnchors.length === 0) {
result = null;
} else if (possibleAnchors.length === 1) {
result = possibleAnchors[0];
} else {
result = possibleAnchors;
}
return result;
});
};