Protractor - testing an Angular form with dynamically populated inputs - angularjs

I am trying to write an e2e test for my angular application, and in particular a form that has 3 select inputs on. The test will need to involve picking random options from these selects. The first select is already populated with data, but the other 2 selects asynchronously populate when the one before has been selected, so they are dependant on each other.
The select inputs also use ng-disabled and only enable when there are options available as per their ng-repeat expressions.
I am using the page object approach with my tests, and so am trying to make some utility functions to achieve the random selection behaviour I need in my tests:
Page Object:
this.selectRandomCustomer = function() {
var option,
randomIndex;
this.customerSelect.click();
this.customerSelectOptions.count().then(function(count) {
randomIndex = Math.floor(Math.random() * count);
option = element(by.repeater('customer in vm.customers').row(randomIndex));
option.click();
});
};
this.selectRandomOrder = function() {
if(this.orderSelect.isEnabled()===true) {
var option,
randomIndex;
this.orderSelect.click();
this.orderSelectOptions.count().then(function(count) {
randomIndex = Math.floor(Math.random() * count);
option = element(by.repeater('order in vm.orders').row(randomIndex));
option.click();
});
}
};
Given that the orderSelect can only be selected once populated with options after choosing an option from the customerSelect, I wondered about hooking into the promise returned when calling this.customerSelectOptions.count(), so calling this.selectRandomOrder, but it seems this is undefined as I get an error from protractor saying it cannot find the selectRandomOrder function.
Right now I can only get the first select to pick an option since it's always populated on the initial page load.
Also, I'm unsure whether using isEnabled() is actually working for me, as I am certain this should be returning true for my second input, but if I console log this out, I see false. Does this not work with ng-disabled?
What are the best practices for dealing with inputs on a form that wont initially be populated with data and waiting for angular to fetch and populate any available options?
Thanks
UPDATE:
I have got this to working using a call to getAttribute() checking for the presence of the disabled property instead.
So from my spec file in an it block I can call
page.customerSelect.getAttribute('disabled').then(function(result){
if(!result) {
page.selectRandomCustomer();
}
});
page.orderSelect.getAttribute('disabled').then(function(result){
if(!result) {
page.selectRandomOrder();
}
});
Ideally what I'd like to be able to do is to call the selectRandomOrder after clicking the option in the selectRandomCustomer:
this.selectRandomCustomer = function() {
var option,
randomIndex;
this.customerSelect.click();
this.customerSelectOptions.count().then(function(count) {
randomIndex = Math.floor(Math.random() * count);
option = element(by.repeater('customer in vm.customer').row(randomIndex));
option.click();
//Like to be able to call selectRandomOrder but only after angular has finished performing AJAX request for data and received response
});
};
this.selectRandomOrder = function() {
var option,
randomIndex;
this.orderSelect.click();
this.orderSelectOptions.count().then(function(count) {
randomIndex = Math.floor(Math.random() * count);
option = element(by.repeater('order in vm.orders').row(randomIndex));
option.click();
});
};
I did try calling this.selectRandomOrder immediately after the option.click() but I get an error saying no such function, it seems this is not accessible from inside the returned promise function callback.

There is at least one major problem in the posted code:
if(this.orderSelect.isEnabled()===true) {
Here isEnabled() returns a promise. You have to resolve it to check it's value:
var self = this; // saving the page object reference
this.orderSelect.isEnabled().then(function (isEnabled) {
if (isEnabled) {
var option,
randomIndex;
self.orderSelect.click();
self.orderSelectOptions.count().then(function(count) {
randomIndex = Math.floor(Math.random() * count);
option = element(by.repeater('order in vm.orders').row(randomIndex));
option.click();
});
}
});

Related

Wait for AngularJS Service to finish running (chrome console)

I'm manipulating some angular services/functions via Chrome console. (I have to specifically do this for a task I'm working on).
What I want to do is wait for the AddBagIfLimitNotReached() function to execute and finish running. And only then access the variable this.option.Quantity.
angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].Scope.AddBagIfLimitNotReached = async function(n) {
console.log("tthis", this)
if (this.HasReachedMaximumBaggageAllowance()) {
angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].LuggageDrawersService.OpenLuggageLimitReachedDrawer();
return;
}
this.AddBag(n);
console.log("Quantity", this.option.Quantity);
};
With this function, I'm adding a product to my basket. And this.option.Quantity should console.log 1. But it actually consoles.log 0.
However, if I check the object itself, it shows 1.
So I think what is happening, is I'm console.logging my bag quantity, before the bag has actually finished being added to the basket.
For example, if I added a settimeout of 2 seconds, the correct bag value = 1 is console.logged.
angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].Scope.AddBagIfLimitNotReached = async function(n) {
console.log("tthis", this)
if (this.HasReachedMaximumBaggageAllowance()) {
angular.element(document.querySelector(".quantity-button")).controller()._registeredControls[1].LuggageDrawersService.OpenLuggageLimitReachedDrawer();
return;
}
this.AddBag(n);
// Returns 1
setTimeout(function(){ console.log("Quantity", this.option.Quantity); }, 2000);
};
Is there a better way I can achieve this, without using settimeout? I have tried async/await/promises, but I still can't seem to find a way to wait for the function to finish loading.
Async/await returns an error - it doesn't like the function this.HasReachedMaximumBaggageAllowance() and throws an error stating this.HasReachedMaximumBaggageAllowance is not a function.
Any tips/ideas would be much appreciated.
I found a solution, I'm using $watch, to watch a key/value, in the this object. And this seems to work:
angular.element(document.querySelector(".quantity-button.plus-button")).controller()._registeredControls[1].Scope.AddBagIfLimitNotReached = function(n) {
let bagCount = this.option.Quantity;
console.log("bagCount", bagCount);
if (this.HasReachedMaximumBaggageAllowance()) {
angular.element(document.querySelector(".quantity-button.plus-button")).controller()._registeredControls[1].LuggageDrawersService.OpenLuggageLimitReachedDrawer();
return;
};
this.AddBag(n);
this.$watch("this.option.Quantity", function (newValue) {
console.log(`Value of foo changed ${newValue}`);
if (newValue > 0) {
document.querySelector(`.luggage-tile-weight-${n.Weight} .tile-title .tick-box`).classList.add("green-tick");
displayGreenTickNoBagSelected();
};
if (newValue === 0) {
document.querySelector(`.luggage-tile-weight-${n.Weight} .tile-title .tick-box`).classList.remove("green-tick");
displayGreenTickNoBagSelected();
};
});
};

E2E tests with multiple pages with information from browser

I am writing an E2E test with protractor. I had to fetch information from the browser and execute a step multiple times.
I am testing one screen which will start when a
User clicks 'Start'
lands on a new page
The workflow below is invoked with count being passed as argument
id the html id does not change. the value changes when queried again after submitting the current form.
for(i = 0 ; i < count ; i++){
console.log("counter is "+i);
element(by('id')).evaluate('value').then(function(v) {
// do some action on UI based on v
element(by('id1')).sendKeys(v+v);
// submit etc.,
// some angular code runs in the frontend.
}
// need to wait since webdriver jumps to the next one without this completing
}
Many blog posts/documentations suggests you cannot use it in a loop, but does not suggest any alternative way to do this.
Any suggestions appreciated.
Never use protractor element statements inside loop: The simple reason is that the webdriverJS (protractor) API is asynchronous. Element statements returns a promise and that promise is in unresolved state while the code below the statements continues to execute. This leads to unpredictable results. Hence, it is advisable to use recursive functions instead of loops.
source: http://engineering.wingify.com/posts/angularapp-e2e-testing-with-protractor/
Edit: updated question with details of workflow.
It is usually not recommended to use a loop when an iteration has an asynchronous call.
The reason is that the first asynchronous calls is executed after the last iteration of the loop when i is already equal to count.
Thus, it makes it difficult to break the loop and to keep track of the value of i.
On way to tackle the issue is to use a recursive function :
var count = 3;
var results = [];
function iterate(i, n) {
if(i < n) {
console.log(`counter is ${i}`);
browser.refresh();
return element(by.id('h-top-questions')).getText().then(function(text) {
results.push(`${i}:${text}`);
return iterate(i + 1, n);
});
}
}
iterate(0, count).then(function(){
console.log("done!", results);
});
But a better way would be to iterate with promise.map on an array sized to the number of iterations:
var count = 3;
protractor.promise.map(Array(count).fill(0), function(v, i) {
console.log(`counter is ${i}`);
browser.refresh();
return element(by.id('h-top-questions')).getText().then(function(text) {
return `${i}:${text}`;
});
}).then(function(results){
console.log("done!", results);
});
You could also keep using a loop. First you'll have to use the let statement to get the value of i in an asynchronous function (ES6).
Then call all the synchronous code with browser.call to synchronize the execution:
var count = 3;
var results = [];
for(let i = 0 ; i < count ; i++){
browser.call(function(){
console.log(`counter is ${i}`);
browser.refresh();
element(by.id('h-top-questions')).getText().then(function(text) {
results.push(`${i}:${text}`);
});
});
}
browser.call(function() {
console.log("done!", results);
});
Looping in protractor works like this
describe('Describe something', function() {
var testParams = [1,2,3,4,5,6,7,8,9,10];
beforeEach( function() {
// ...
});
for (var i = 0; i < testParams.length; i++) {
(function (testSpec) {
it('should do something', function() {
// inside loop
});
})(testParams[i]);
};
});
Edit : I might be mis-understanding your question, but it seems to me you want to complete all(dynamic count) actions on the page, before going to the next one ?
it('should clear old inspections', function() {
inspectieModuleInspectieFixture.getRemoveInspectionButton().count().then(function (value) {
if(value == 0){
console.log('--- no inspections to remove ---');
}
for(var i = 0; i < value; i++){
//global.waitForClickable(inspectieModuleInspectieFixture.getRemoveInspectionButtonList(i+1));
inspectieModuleInspectieFixture.getRemoveInspectionButtonList(i+1).click();
console.log('iteration '+i + 'count '+value )
};
});
global.wait(5000);
}); */
this counts elements on the page and then it performs an action for the ammount of elements it found
In the above example I use containers to hold my elements, so my code remains readable (i.e. inspectieModuleInspectieFixture.getRemoveInspectionButton() holds $(".elementSelectorExample")
There is also a 'global.waitForClickable' commented, that is reffering to a 'time module' I've created that extends the functionality of 'wait', in this case it waits till the element is vissible/clickable.
This is easily mirrored perhaps something like this :
waitForElementNoDisplay: function(element){
return browser.wait(function() {
return element.isDisplayed().then(function(present) {
return !present;
})
});
},
this will make protractor WAIT untill an element is no longer displayed.(Display:none)
If you need to perform some action on every element, it is true, that better to not use loops. Use .map() or .each() or .filter() instead
Still not quite sure what you what to do, but here is example how i am doing similar tasks, when you need to make number of actions depending on data from the page:
class SomePage {
typeValueForEachElement(elements) {
elements.each((elem, index)=> {
elem.getAttribute('value').then(value=> {
elem.sendKeys(value + value)
elem.submit()
})
})
}
}
new SomePage().typeValueForEachElement($$('your locator here'))
Here is api reference that might help
http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.map
http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.reduce
http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.each
http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.filter

tell Protractor to wait for the page before executing expect

When I click the export button, it makes a REST call to our endpoint then few seconds after, I receive the response then I also render the table. Unfortunately, I read that every call is asynchronous which means my expect will be executed even if table hasn't been rendered yet. The expect I wrote checks if the string is on the table but it's failing since it's not there yet. What is the proper approach to this?
it('should generate global user report', function() {
element(by.css('button#exportButton')).click();
expect(element(by.css("th[name*=Date]")).getText()).
toEqual('Date');
})
The error on the console is
NoSuchElementError: No element found using locator: By.cssSelector("th[name*=Date]")
I noticed that the table hasn't been rendered yet that's why it's failing.
Protractor 1.7 introduced a feature called "Expected Conditions", that can be applied here.
Wait for element to become visible:
var EC = protractor.ExpectedConditions;
var elm = element(by.css("th[name*=Date]"));
browser.wait(EC.visibilityOf(elm), 5000);
expect(elm.getText()).toEqual('Date');
I had problem waiting for a dynamic element to appear. Have the driver wait for it to either be present or displayed. The number at the end is the timeout.
element(by.css('button#exportButton')).click();
var header = element(by.css("th[name*=Date]"));
browser.driver.wait(function() {
return header.isPresent();
}, 1000);
expect(header.getText()).toEqual('Date');
I had to wait until it was present AND displayed before the test was fully stable. You can do that like this:
var header = element(by.css("th[name*=Date]"));
browser.driver.wait(function() {
return header.isPresent().then(function(present) {
if (present) {
return header.isDisplayed().then(function(visible) {
return visible;
});
} else {
return false;
}
});
}, 1000);

How do you tell when a view is loaded in extjs?

Im working on an extjs application. We're have a page that is for looking at a particular instance of an object and viewing and editing it's fields.
We're using refs to get hold of bits of view in the controller.
This was working fine, but I've been sharding the controller into smaller pieces to make it more managable and realised that we are relying on a race condition in our code.
The logic is as follows:
Initialise the controller
parse the url to extract the id of the object
put in a call to load the model with the given view.
in the load callback call the controller load method...
The controller load method creates some stores which fire off other requests for bits of information using this id. It then uses some of the refs to get hold of the view and then reconfigures them to use the stores when they load.
If you try and call the controller load method immediately (not in the callback) then it will fail - the ref methods return undefined.
Presumably this is because the view doesnt exist... However we aren't checking for that - we're just relying on the view being loaded by the time the server responds which seems like a recipe for disaster.
So how can we avoid this and be sure that a view is loaded before trying to use it.
I haven't tried rewriting the logic here yet but it looks like the afterrender event probably does what I want.
It seems like waiting for both the return of the store load and afterrender events should produce the correct result.
A nice little abstraction here might be something like this:
yourNamespace.createWaitRunner = function (completionCallback) {
var callback = completionCallback;
var completionRecord = [];
var elements = 0;
function maybeFinish() {
var done = completionRecord.every(function (element) {
return element === true
});
if (done)
completionCallback();
}
return {
getNotifier: function (func) {
func = func || function (){};
var index = elements++;
completionRecord[index] = false;
return function () {
func(arguments);
completionRecord[index] = true;
maybeFinish();
}
}
}
};
You'd use it like this:
//during init
//pass in the function to call when others are done
this.waiter = yourNamespace.createWaitRunner(controller.load);
//in controller
this.control({
'SomeView': {
afterrender: this.waiter.getNotifier
}
});
//when loading record(s)
Ext.ModelManager.getModel('SomeModel').load(id, {
success: this.waiter.getNotifier(function (record, request) {
//do some extra stuff if needs be
me.setRecord(record);
})
});
I haven't actually tried this out yet so it might not be 100% but I think the idea is sound

angular-ui-select2 and breezejs: load ajax list after typing in 2 characters

I have a project where I'm using BreezeJS to fetch data from my webserver. I'm using AngularJS with the ui-select2 module. Currently, I have it where when I load my page, breezejs makes a call to fetch the data that I dump into a scope variable. From there, select2 can easily make the reference to it and build accordingly.
If I want to ajaxify things, it gets really tricky. I want to have the ability to use select2's ajax or query support, but instead of using it to fetch data, I want to use breezejs to do it. So during a page load, nothing is loaded up until I start typing in X minimum characters before it makes an ajax fetch.
Constraints:
I do not want fetch data using select2's "ajax". I want BreezeJS to handle the service calls. When I use ajax, it makes an ajax call everytime I press a character in order to filter the results (and resemble autocomplete). I just want the list to load up once and use the native filtering after that.
Here is what I have so far:
breezejs - StateContext.JS
m.app.factory('StateContext', ['$http', function ($http) {
configureBreeze();
var dataService = new breeze.DataService({
serviceName: "/Map/api",
hasServerMetadata: false
});
var manager = new breeze.EntityManager({ dataService: dataService});
var datacontext = {
getAllStates: getAllStates
};
return datacontext;
function getAllStates() {
var query = breeze.EntityQuery
.from("States");
return manager.executeQuery(query);
}
function configureBreeze() {
breeze.config.initializeAdapterInstances({ dataService: "webApi" });
}
}]);
This works and returns my json object correctly.
Here is how I call the service:
m.app.controller('LocationCtrl', ['$scope', 'StateContext', function ($scope, StateContext) {
$scope.getAllStates = function () {
StateContext.getAllStates().then(stateQuerySucceeded).fail(queryFailed);
}
$scope.getAllStates();
$scope.states = [];
function stateQuerySucceeded(data) {
data.results.forEach(function (item) {
$scope.states.push(item);
});
$scope.$apply();
console.log("Fetched States");
}
function queryFailed(error) {
console.log("Query failed");
}
$scope.select2StateOptions = {
placeholder: "Choose a State",
allowClear: true,
minimumInputLength: 2
};
}
and here is my html:
<div ng-app="m" id="ng-app">
...
...
<select ui-select2="select2StateOptions" ng-model="LocationModel.State">
<option value=""></option>
<option ng-repeat="state in states" value="{{state.id}}">{{state.name}}</option>
</select>
</div>
Currently the html select2 control loads up when the page loads. But I want to have it so when I type in more than 2 characters, I'll be able to make the call to $scope.getAllStates(); as an ajax call. BreezeJS already uses ajax natively when configuring the BreezeAdapter for webapi.
I was thinking about using select2's ajax, or query calls.. but I'd rather use breeze to fetch the data, since it makes querying extendable, and I don't want to violate my design pattern, or make the code harder to maintain, and I don't want the ajax calls to be made everytime I enter a new character into the textbox, I just want it to occur once.
Close attempt:
changed my html to:
<!-- Select2 needs to make this type="hidden" to use query or ajax, then it applies the UI skin afterwards -->
<input type="hidden" ui-select2="select2StateOptions" ng-model="LocationModel.State" /><br />
in my controller, changing select2StateOptions:
$scope.select2StateOptions = {
placeholder: "Choose a State",
allowClear: true,
minimumInputLength: 2,
query: function (query) {
debugger;
var data = StateContext.getAllStates().then(stateQuerySucceeded).fail(queryFailed);
}
};
Here's the problem. BreezeJS uses a Q library, which makes use of a thing called a "promise"; which is a promise that data will be returned after making the ajax call. The problem with this, the query function is expecting data to be populated, but the promise to call the "stateQuerySucceeded" function is made after returning from the query function.
So it hits the query function first. Then hits getAllStates(). Returns from the query (nothing is populated), then "stateQuerySucceeded" is called after that.
In otherwords, even though I have been able to fetch data, this is done too late.. select2's query function did not receive the data at the right time, and my html select is hanging on "Searching ... " with a search spinner.gif.
I don't really know this angular-ui-select2 control. I think the relevant part of the documentation is this example:
$("#e5").select2({
minimumInputLength: 2,
query: function (query) {
var data = {results: []}, i, j, s;
// simulate getting data from the server
for (i = 1; i < 5; i++) {
s = "";
for (j = 0; j < i; j++) {s = s + query.term;}
data.results.push({id: query.term + i, text: s});
}
query.callback(data);
}
});
I will leave aside the fact that you don't seem to be interested in using the two-or-more characters that the user enters in your query (maybe you just left that out). I'll proceed with what seems to me to be nonsense, namely, to fetch all states after the user types any two letters.
What I think you're missing is the role of the query.callback which is to tell "angular-ui-select2" when the data have arrived. I'm guessing you want to call query.callback in your success function.
$scope.select2StateOptions = {
placeholder: "Choose a State",
allowClear: true,
minimumInputLength: 2,
query: function (query) {
StateContext.getAllStates()
.then(querySucceeded).catch(queryFailed);
function querySucceeded(response) {
// give the {results:data-array} to the query callback
query.callback(response);
}
function queryFailed(error) {
// I don't know what you're supposed to do.
// maybe return nothing in the query callback?
// Tell the user SOMETHING and then
query.callback({results:[]});
}
}
};
As I said, I'm just guessing based on a quick reading of the documentation. Consider this answer a "hint" and please don't expect me to follow through and make this actually work.

Resources