[英]How to select a visible element in Protractor with Angularjs
我有一個 SPA,其中有多個具有相同類的 div。 我希望量角器選擇可見的 div 並單擊它。 我不斷收到Failed: element not visible
,這讓人相信它正在獲取一些不在此特定頁面上的元素(也許?)。 我還收到WARNING - more than one element found for locator By.cssSelector('.myDiv') - the first result will be used
,這再次讓我認為它不是點擊可見的,而是不可見的。
這是我的規格:
describe('User actions', function () {
it("should be able to click a my div.", function () {
var myDiv = element(by.css('.myDiv'));
myDiv.click();
// some expect... haven't gotten this far yet.
});
如何選擇可見的.myDiv
並單擊它?
你可以filter()
出來:
var myDiv = element.all(by.css('.myDiv')).filter(function (elm) {
return elm.isDisplayed().then(function (isDisplayed) {
return isDisplayed;
});
}).first();
使用 angular 時,隱藏同一位 html 的許多層是很常見的,但在整個 html 頁面中比您想要使用的可見元素更早。
對於一般調試,將站點打開到您希望量角器測試所在的位置,然后打開 html 並在 html 上搜索量角器測試正在搜索的元素。 請注意它是否可見以及它的整體位置。
考慮是否要為元素可以出現的頁面的不同區域添加一個標簽,然后使用父選擇器和子選擇器來獲得您想要的。
您還可以使用它來僅選擇第一個可見元素:
// Takes a protractor webelement and returns the first displayed version
// Ex:
// var coolBox = $('.coolBox');
// var visibleCoolBox = getFirstVisibleProtractorElement(coolBox);
this.getFirstVisibleProtractorElement = function(selector){
var allElementsOfSelector = element.all(by.css(selector.locator().value));
return allElementsOfSelector.filter(function(elem) {
return elem.isDisplayed().then(function(displayedElement){
return displayedElement;
});
}).first();
};
傳入您想要的任何元素,它將獲取定位器並獲得它的第一個可見版本。 您還可以去掉 .first() 部分以返回要使用的可見元素數組。
編輯:
為了使用這個,我將給出一個量角器+茉莉花的例子。 我認為這應該可行,因為頁面上有任意數量的所需元素,至少有一個可見。 不過,這不在我的腦海中,所以我可能在某個地方犯了錯誤。
example_spec.js
var examplePage = require('./example_page.js');
describe('Extracting visible elements', function(){
it('A visible element can be extracted', function(){
expect(examplePage.isACoolBoxVisible()).toBeTruthy('Error: No visible CoolBoxes');
});
});
example_page.js
var protractorUtils = require('./protractor_utils.js');
module.exports = new function(){
var elements = {
coolBox: $('.coolBox')
};
this.getVisibleCoolBox = function(){
return protractorUtils.getFirstVisibleProtractorElement(elements.coolBox);
};
this.isACoolBoxVisible = function(){
return getVisibleCoolBox.isDisplayed();
};
};
量角器_utils.js
module.exports = new function(){
this.getFirstVisibleProtractorElement = function(selector){
var allElementsOfSelector = element.all(by.css(selector.locator().value));
return allElementsOfSelector.filter(function(elem) {
return elem.isDisplayed().then(function(displayedElement){
return displayedElement;
});
}).first();
};
};
我的答案中的邏輯和技術實際上是相同的,但我發現我的解決方案更可重用。
定義一個像下面這樣的函數
getFirstDisplayed(locator: Locator) {
return element.all(locator).filter(x => x.isDisplayed()).first();
}
然后只需將您的語句轉換為
element(by.css('img[title="Delete query rule"]')).click();
到
getFirstDisplayed(by.css('img[title="Delete query rule"]')).click();
這樣,您將單擊第一個顯示的項目
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.