问题
I'm trying to get the specific ElementFinder from an ElementArrayFinder based on the text of the desired element.
For example, suppose I have the following HTML snippet provided by an Angular2 app:
<ul id="names">
<li><span>Adam</span> <span class="ids">ID: 1</span></li>
<li><span>Becky</span> <span class="ids">ID: 2</span></li>
<li><span>Chris</span> <span class="ids">ID: 3</span></li>
</ul>
And I want to select the second li using the name "Becky". So I have the following function:
/**
* Get a Card object that contains the ElementFinder of a specific <li>
* @param desiredName {string} The name to search on the row
* @returns {Card} A Card object with a "verifyID" method.
*/
getCardByName(desiredName) {
return $$('#names li').map(function(el) {
return el.$('span:first-child').getText().then(function(name) {
console.log("getCardByName: got the card for " + name);
if (name === desiredName) {
console.log("getCardByName: returning card");
return new Card(el); // el should be pointing to an <li> element
}
});
});
}
I then call that function by doing:
it('test Becky', function(done) {
getCardByName("Becky").then(function(card) {
console.log("SPEC: testing card");
card.verifyId("ID: 2");
done();
})
.catch(function(err) { console.log(err); });
});
The output that I'm getting is, I wait a long time and then see:
getCardByName: got the card for Adam
getCardByName: got the card for Becky
getCardByName: returning card
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
With my current solution, I keep running into the issue described here: https://github.com/angular/protractor/issues/2227
I am uncertain as to whether I am doing something wrong or can improve my code, or if I really am running up against the issue described in the bug report linked above.
For what it's worth, assume the Card object looks like:
function Card(containerEl) {
this.containerEl = containerEl;
}
Card.prototype = {
constructor: Card,
verifyId: function(expectedId) {
var el = this.containerEl.$('span.ids');
expect(el.getText()).toEqual(expectedId);
}
}
回答1:
you can use filter() function to do the task
var rows = element(by.id('names'));
var becky = rows.all(by.tagName('li')).filter(function (elem) {
return elem.getText().then(function (val) {
return val === 'Becky'
});
}).first();
来源:https://stackoverflow.com/questions/40730037/get-a-specific-element-from-an-elementarrayfinder-in-protractor-based-on-the-tex