Reputation: 75
I'm testing a web page with the following elements in it:
<span class="step-count ng-binding">1</span>
<span class="step-count ng-binding">2</span>
<span class="step-count ng-binding">3</span>
<span class="step-count ng-binding">4</span>
First I want to count them so I've tried the following code:
it('make sure all elements exist at page', function() {
var x = browser.findElements(by.css('.step-count.ng-binding'));
expect(x.length).toEqual(4);
});
and
it('make sure all elements exist at page', function() {
var x = browser.findElements(by.css('.step-count.ng-binding'));
expect(x.size).toEqual(4);
});
Both produced a failure message:
Failures: Expected undefined to equal 4.
How do I count them properly in my ProtractorJS project and how do I iterate over them afterwards in order to compare text or any other properties that might be added later?
Upvotes: 1
Views: 2542
Reputation: 473873
You are overcomplicating the problem. Using $$()
and .count()
and .getText()
:
var elements = $$('.step-count');
expect(elements.count()).toEqual(4);
expect(elements.getText()).toEqual(["1", "2", "3", "4"]);
Note how we don't need to resolve into the array of elements - both count()
and getText()
methods are available on the ElementArrayFinder
(the result of element.all()
or $$()
) and the expect()
in Jasmine/Protractor knows what a promise is and would resolve it before making an expectation.
Also note that it is not a good idea to use ng-binding
class in your locators - it is a pure technical Angular class that doesn't provide any valuable, unique, data-oriented and meaningful information. If you want to enforce not having Angular classes or other technical attributes used inside locators, you can use ESLint
static code analysis tool and eslint-plugin-protractor
plugin which has the no-angular-classes
and no-angular-attributes
relevant rules.
Upvotes: 4
Reputation: 75
I want to thank @GillesC and @Suresh Salloju for the following code that worked for me:
it('make sure all elements exist at page', function() {
var x = element.all(by.css('.step-count.ng-binding')).then(function (items) {
expect(items.length).toBe(4);
});
for (let i = 1; i < x.length; ++i) {
expect(x[i].getText()).toBe(i.toString());
}
});
Upvotes: 0
Reputation: 2547
You can use element.all()
to find all the elements with same locator in Protractor. Use the following code:
element.all(by.css('.step-count.ng-binding')).then(function(listOfElements){
//verify the count of elements
expect(listOfElements.count()).toEqual(4);
//iterate on list of elements
listOfElements.each(function(eachElement){
eachElement.getText().then(function(text){
console.log("Ele Text:"+text);
});
});
});
Upvotes: 0