【问题标题】:Get a specific element from an ElementArrayFinder in protractor based on the text of getText()根据 getText() 的文本从量角器中的 ElementArrayFinder 获取特定元素
【发布时间】:2026-02-03 17:35:01
【问题描述】:

我正在尝试根据所需元素的文本从 ElementArrayFinder 中获取特定的 ElementFinder。

例如,假设我有一个 Angular2 应用程序提供的以下 HTML sn-p:

<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>

我想使用名称“Becky”选择第二个 li。所以我有以下功能:

/**
 * 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
            }
        });
    });
}

然后我通过以下方式调用该函数:

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); });
});

我得到的输出是,我等了很长时间,然后看到:

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

使用我目前的解决方案,我一直遇到这里描述的问题:https://github.com/angular/protractor/issues/2227

我不确定我是否做错了什么或可以改进我的代码,或者我是否真的遇到了上面链接的错误报告中描述的问题。

对于它的价值,假设 Card 对象看起来像:

function Card(containerEl) {
    this.containerEl = containerEl;
}

Card.prototype = {
    constructor: Card,
    verifyId: function(expectedId) {
        var el = this.containerEl.$('span.ids');
        expect(el.getText()).toEqual(expectedId);
    }
}

【问题讨论】:

    标签: protractor


    【解决方案1】:

    您可以使用 filter() 函数来完成任务

     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();
    

    【讨论】:

    • 这对我有用,但它在我的 6 行数组中运行了 13 次。我会问另一个关于那个的问题。 *.com/questions/40745593/…