根据getText()

时间:2016-11-21 21:49:28

标签: protractor

我试图根据所需元素的文本从ElementArrayFinder获取特定的ElementFinder。

例如,假设我有一个Angular2应用程序提供的以下HTML代码段:

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

我想选择名为&#34; Becky&#34;的第二个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);
    }
}

1 个答案:

答案 0 :(得分: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();