Protractor select values from drop down with promise - angularjs

I'm running a protractor tests and filling in a form with dropdowns. How can I ensure that each dropdown has a promise that is resolved before moving onto the next one? Right now I'm using sleeps and know that can't be the right way.
Describe('Filling site utility form', function() {
beforeEach(function(){
var input_monthly = by.linkText('Input Monthly');
browser.wait(function() {
return browser.isElementPresent(input_monthly);
});
var field1 = element(by.id('field1'));
Test.dropdown(field1, 1);
var field2 = element(by.id('field2'));
Test.dropdown(field2, 1);
});
My dropdown function is:
dropdown = function(element, index, milliseconds) {
element.findElements(by.tagName('option'))
.then(function(options) {
options[index].click();
});
if (typeof milliseconds !== 'undefined') {
browser.sleep(milliseconds);
}
}

Not 100% sure what you mean but I suspect what you're interested in is this:
describe('Filling site utility form', function() {
beforeEach(function(){
var input_monthly = by.linkText('Input Monthly');
browser.wait(function() {
return browser.isElementPresent(input_monthly);
});
var promise1 = element(by.id('field1')).all(by.tagName('option')).get(1).click();
var promise2 = element(by.id('field2')).all(by.tagName('option')).get(1).click();
protractor.promise.all([promise1, promise2]).then(function() {
//what do you want to do next?
});
});
});

Related

AngularJS How to execute function after some function finish?

I have some page which contain register with facebook button which I set hidden with ng-hide="fbLoggedIn" and form input which I set hidden with ng-show="fbLoggedIn"
My goal is register with facebook button will hide if fbLoggedIn set to true and form input will show if fbLoggedIn set to true.
register facebook button ng-click="registerFb()" execute this function
$scope.registerFB = function () {
authService.fbLogin();
$scope.fbLoggedIn = authService.fb_logged_in();
console.log($scope.fbLoggedIn); //this show false even `fb_access_token` not null
}
Here is my authService.fbLogin and authService.fb_logged_in function
authService.fbLogin = function () {
var FB = window.FB;
FB.login(function(response) {
console.log(response);
if (response.authResponse) {
sessionService.set('fb_id', response.authResponse.userID);
sessionService.set('fb_access_token', response.authResponse.accessToken);
sessionService.set('fb_expiration_date', new Date(new Date().getTime() + response.authResponse.expiresIn * 1000).toISOString());
//console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
console.log(response);
});
} else {
console.log('User cancelled login or did not fully authorize.');
//console.log(response);
}
});
};
authService.fb_logged_in = function () {
if(sessionService.get('fb_access_token') != null){
return true;
}else {
return false;
}
};
In other function I try to check if fb_access_token is not null, just to make sure something wrong with my logic, and the result is true.
With above debuggin I can say that $scope.fbLoggedIn = authService.fb_logged_in(); execute before authService.fbLogin(); finish.
So how I can execute $scope.fbLoggedIn = authService.fb_logged_in(); after authService.fbLogin(); finish? maybe how to achieve my goal?
Alright. This can be achieved using promise. I don't know the parameters you have included in your autService service, so I will be making a factory of the same name with the new parameters that you might need to add.
Hence, according to me, this is how your factory should be.
angular.module('YourModuleName').factory('authService',['$http','$q',function($http,$q){
var obj = {};
obj.fbLogin = function () {
var defer = $q.defer();
var FB = window.FB;
FB.login(function(response) {
console.log(response);
if (response.authResponse) {
sessionService.set('fb_id', response.authResponse.userID);
sessionService.set('fb_access_token', response.authResponse.accessToken);
sessionService.set('fb_expiration_date', new Date(new Date().getTime() + response.authResponse.expiresIn * 1000).toISOString());
FB.api('/me', function(response) {
console.log(response);
defer.resolve('Good to see you, ' + response.name + '.');
});
}
else {
defer.reject('User cancelled login or did not fully authorize.');
}
});
return defer.promise;
}
obj.fb_logged_in = function () {
if(sessionService.get('fb_access_token') != null){
return true;
}else {
return false;
}
};
return obj;
}])
And thus, the function call from the controller should be as follows.
$scope.registerFB = function () {
authService.fbLogin().then(function(response){
$scope.fbLoggedIn = authService.fb_logged_in();
console.log($scope.fbLoggedIn);
},function(error){
console.error("Error : ",error);
});
}
Note: CODE NOT TESTED.
Hence it would solve the problem with the best practices of angularJS
use the $rootscope to assign values they provide event emission/broadcast and subscription facility.

No popup window with AngularJS and typeahead

I have a problem with the typeahead directive. I try to get datas from my datas from my service via $http.get.
In the console output I can see that my datas are coming from the service but I don't get the popup window of the results.
Here is my code:
Html Template:
<input type="text" class="form-control" placeholder="Kundensuche" ng-model="selectedCompany" typeahead="c for c in companies($viewValue)" typeahead-no-results="noResults" typeahead-min-length="3">
Service:
var _search = function (route, id) {
return $http.get(serviceBase + 'api/' + route + '/search/' + id);
};
serviceHelperFactory.search = _search;
Controller:
$scope.companies = function (val) {
var output = [];
var promise = serviceHelper.search('companies', val);
promise.then(function (result) {
result.data.forEach(function (company) {
output.push(company.companyName);
//output.push(company);
});
console.log(output);
}, function (error) {
adminInvoiceService.serviceErrorMessage(error);
});
return output;
}
Thanks!
Ok, I fixed it!
For all with the same problem here is my solution!
$scope.companies = function (val) {
return $http.get('http://localhost:5569/api/companies/search/'+val).then(function (res) {
var companies = [];
console.log(companies);
res.data.forEach(function (item) {
companies.push(item);
});
console.log(companies);
return companies;
});
};

How to lazy load Firebase data using ionic infinite scroll

I have a set of data within a users profile which holds the UID of all the posts they have liked. I am using a data snapshot to show these images within the users profile, but I would like to load it lazy or use ionic infinite scroll to load more items as the user scrolls.
I tried by making two duplicate snap shots. First one intialises the feed upon the page loading, and then I wanted the second one to load by using ionic infinite scroller.
But it doesn't work.
Does anyone know of a better way to do this?
service.js
getWardrobeFeed: function(){
var defered = $q.defer();
var user = User.getLoggedInUser();
var wardrobeKeyRef = new Firebase(FIREBASE_URL + '/userProfile/' + user.uid + '/wardrobe');
wardrobeKeyRef.orderByKey().limitToLast(2).on('child_added', function (snap) {
var imageId = snap.key();
userImageRef.child(imageId).on('value', function (snap) {
$timeout(function () {
if (snap.val() === null) {
delete userWardrobeFeed[imageId];
} else {
userWardrobeFeed[imageId] = snap.val();
}
});
});
});
wardrobeKeyRef.orderByKey().limitToLast(2).on('child_removed', function (snap) {
var imageId = snap.key();
$timeout(function () {
delete userWardrobeFeed[imageId];
});
});
defered.resolve(userWardrobeFeed);
return defered.promise;
},
getWardrobeItems: function(){
var defered = $q.defer();
var user = User.getLoggedInUser();
var wardrobeKeyRef = new Firebase(FIREBASE_URL + '/userProfile/' + user.uid + '/wardrobe');
wardrobeKeyRef.orderByKey().limitToFirst(2).on('child_added', function (snap) {
var imageId = snap.key();
userImageRef.child(imageId).on('value', function (snap) {
$timeout(function () {
if (snap.val() === null) {
delete userWardrobe[imageId];
} else {
userWardrobe[imageId] = snap.val();
}
});
});
});
wardrobeKeyRef.orderByKey().on('child_removed', function (snap) {
var imageId = snap.key();
$timeout(function () {
delete userWardrobe[imageId];
});
});
defered.resolve(userWardrobe);
return defered.promise;
},
controller.js
$scope.userWardrobe = [];
Service.getWardrobeFeed().then(function(items){
$scope.userWardrobe = items;
});
$scope.loadMore = function() {
Service.getWardrobeItems().then(function(items){
$scope.userWardrobe = $scope.userWardrobe.concat(items);
$scope.$broadcast('scroll.infiniteScrollComplete');
});
};

AngularJS hide div after delay

While creating my app in AngularJS (awesome framework!) I stuck in one task: how to show and hide hidden div (ng-show) after some action.
Detailed description: using AngularUI $modal service I'm asking if user wants to perform action, if yes, I run service to POST request via $http to send which item I want to delete. After it finished I want to show hidden div with information, that process has accomplished successfully. I created a simple service with $timeout to set div's ng-show and hide after some time but it doesn't update variable assigned to ng-show directive. Here is some code:
Controller for listing and deleting items
$scope.deleteSuccessInfo = false; //variable attached to div ng-show
$scope.deleteCluster = function(modalType, clusterToDelete) {
modalDialogSrvc.displayDialog(modalType)
.then(function(confirmed) {
if(!confirmed) {
return;
}
clusterDeleteSrvc.performDelete(itemToDelete)
.then(function(value) {
//my attempt to show and hide div with ng-show
$scope.deleteSuccessInfo = showAlertSrvc(4000);
updateView(itemToDelete.itemIndex);
}, function(reason) {
console.log('Error 2', reason);
});
}, function() {
console.info('Modal dismissed at: ' + new Date());
});
};
function updateView(item) {
return $scope.listItems.items.splice(item, 1);
}
Part of service for deleting item
function performDelete(itemToDelete) {
var deferred = $q.defer(),
path = globals.itemsListAPI + '/' + itemToDelete.itemId;
getDataSrvc.makeDeleteRequest(path)
.then(function() {
console.log('Item removed successfully');
deferred.resolve({finishedDeleting: true});
}, function(reason) {
console.log('error ', reason);
deferred.reject(reason);
});
return deferred.promise;
}
return {
performDelete: performDelete
};
Simple service with $timeout to change Boolean value after some time
angular.module('myApp')
.service('showAlertSrvc', ['$timeout', function($timeout) {
return function(delay) {
$timeout(function() {
return false;
}, delay);
return true;
};
}]);
I tried $scope.$watch('deleteSuccessInfo', function(a, b) {...}) with no effect. How to apply false after some delay? Or maybe You would achieve this in other way?
Thank You in advance for any help!
Change the implementation of the showAlertSrvc service, like this:
angular.module('myApp')
.service('showAlertSrvc', ['$timeout', function($timeout) {
return function(delay) {
var result = {hidden:true};
$timeout(function() {
result.hidden=false;
}, delay);
return result;
};
}]);
And then change thes 2 lines:
The declaration of deleteSuccessInfo should be like this:
$scope.deleteSuccessInfo = {};
And then do this:
$scope.deleteSuccessInfo = showAlertSrvc(4000);
And finally in your view do this "ng-show=!deleteSuccessInfo.hidden"
Example

Angular js not updating dom when expected

I have a fiddle for this, but basically what it's doing it geo-encoding an address that is input into a textbox. After the address is entered and 'enter' is pressed, the dom does not immediately update, but waits for another change to the textbox. How do I get it to update the table right after a submit?
I'm very new to Angular, but I'm learning. I find it interesting, but I have to learn to think differently.
Here is the fiddle and my controller.js
http://jsfiddle.net/fPBAD/
var myApp = angular.module('geo-encode', []);
function FirstAppCtrl($scope, $http) {
$scope.locations = [];
$scope.text = '';
$scope.nextId = 0;
var geo = new google.maps.Geocoder();
$scope.add = function() {
if (this.text) {
geo.geocode(
{ address : this.text,
region: 'no'
}, function(results, status){
var address = results[0].formatted_address;
var latitude = results[0].geometry.location.hb;
var longitude = results[0].geometry.location.ib;
$scope.locations.push({"name":address, id: $scope.nextId++,"coords":{"lat":latitude,"long":longitude}});
});
this.text = '';
}
}
$scope.remove = function(index) {
$scope.locations = $scope.locations.filter(function(location){
return location.id != index;
})
}
}
Your problem is that the geocode function is asynchronous and therefore updates outside of the AngularJS digest cycle. You can fix this by wrapping your callback function in a call to $scope.$apply, which lets AngularJS know to run a digest because stuff has changed:
geo.geocode(
{ address : this.text,
region: 'no'
}, function(results, status) {
$scope.$apply( function () {
var address = results[0].formatted_address;
var latitude = results[0].geometry.location.hb;
var longitude = results[0].geometry.location.ib;
$scope.locations.push({
"name":address, id: $scope.nextId++,
"coords":{"lat":latitude,"long":longitude}
});
});
});

Resources