2016-05-12 44 views
2

我需要做一個斷言來檢查元素是否存在於「elements.all」中。量角器檢查元素是否存在於LIST中使用element.all

我的第一個想法是運行一個for循環,並把期望放在裏面。不是一個好主意,因爲它正在檢查列表中的每一項。所以如果我有30個項目,我可能會失敗29。

element.all(by.css(element)).then(function(itemList) { 
 
    console.log("Total values in dropdown are: " + itemList.length); 
 
    for (i = 0; i < itemList.length; i++) { 
 
    itemList[i].getText().then(function(text) { 
 
     console.log(text); 
 
     expect(text).toEqual('whatever-i-need-to-assert'); 
 
    }); 
 
    }; 
 
});

爲了解決這個問題,我窩IF語句,將「預檢查」的字符串匹配。另一個壞主意,因爲如果沒有比賽,我希望永遠不會運行,因此,給我一個假合格:

element.all(by.css(".item a.gc-exercises-link")).then(function(itemList) { 
 
    console.log("Total values in dropdown are: " + itemList.length); 
 
    for (i = 0; i < itemList.length; i++) { 
 
    itemList[i].getText().then(function(text) { 
 
     console.log(text); 
 
     if (text == 'BOATLIFT-EXERCISE') { 
 
     console.log('Match'); 
 
     expect(text).toEqual('BOATLIFT-EXERCISE'); 
 
     } else { 
 
     console.log('No Match'); 
 
     }; 
 
    }); 
 
    }; 
 
});

很顯然,我在這裏走錯了路。有人可以給我一個想法,當使用element.all時,如何正確地期望「文本」。我只需要證明上述清單中有一段文字。

謝謝!

回答

0

如果你只是要檢查它的存在(和其他列表項的不會干擾),你可以調用element.all後的陣列上.getText().then前和使用toContain()

element.all(by.css(".item a.gc-exercises-link")).getText().then(function(itemList) { 
    expect(itemList).toContain('some text'); 
}; 

或者,如果你知道這個指數:

element.all(by.css(".item a.gc-exercises-link")).getText().then(function(itemList) { 
    expect(itemList[3]).toEqual('some text'); 
} 

作爲一個方面說明:您可以使用.each(),而不是爲循環創建https://angular.github.io/protractor/#/api?view=ElementArrayFinder.prototype.each

0

您可以使用過濾功能。

$$("span").filter(function(elem,index){ 
    return elem.getText().then(function(txt){ 
     return txt === 'text to compare'; 
    }); 
}).then(function(eleList){ // you get the list of elements containing the text here 
    console.log(eleList.length); 
}); 
2

下面是一個例子,以檢查是否有與在一個頁面中的文本「條款」的鏈接:

browser.get('https://www.google.co.uk/'); 
expect(element.all(by.css('a')).getText()).toContain('Terms'); 

注意,對於每一個元素,量角器需要interogate瀏覽器,這可能特別是如果有很多元素時會變慢。

一個更快的解決辦法是檢查並確保至少一個元素存在與包括預期文字的XPath:

browser.get('https://www.google.co.uk/'); 
expect(element.all(by.xpath("//a[text()='Terms']")).count()).toBeGreaterThan(0); 
+0

謝謝!這一個工作。我在列表中找到一個近30-100個索引長的項目。並且在測試之後,我只在測試中添加了大約2秒。在我這個階段可以接受的東西。再次感謝! – Ross