Get a specific element from an ElementArrayFinder in protractor based on the text of getText()

三世轮回 提交于 2020-01-23 15:38:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!