【发布时间】:2016-12-11 04:20:51
【问题描述】:
我正在使用量角器和黄瓜框架;如何摆脱 .filter 或 .map 循环?如果找到匹配项,我不想继续进一步迭代!
Page.prototype.getElementByKey = function (key) {
var foundElement = null;
return someElement.all(by.css('.someClass')).map(function (rawItem, index) {
var itemObject = new ItemObjectClass(rawItem);
return itemObject.getItemKey().then(function (foundItemKey) {
var matched = String(foundItemKey).trim() === String(key).trim();
console.log(' Matched: { ' + matched + ' } index {'+index+'}');
//if we have a match break out of the .filter function
if (matched) {
foundElement = itemObject;
throw new Error("Just our way of breaking out of .filter() above");
}
});
}).then(function () {
//callback
throw new Error('\n!!!!!Callback should not be called;
this means that we could not find an element that matched the passed in key above');
}, function (error) {
//error
console.log('\n*******************errorCallback was called; '+error);
return foundElement;
});
};
上面的代码找到了元素,但继续迭代直到结束,而不是在匹配时停止并通过调用 errorCallback 函数中断。
鉴于 .map 函数返回“解析为 map 函数返回的值数组的承诺”http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.map,我正在利用如果 promise 无法解决,promise 将调用它的 errCallback。
通过抛出一个虚假的错误,应该调用 errorCallback 从而跳出 .map 循环。
不幸的是,它成功抛出错误但继续循环而不是中断。我知道,因为当我
console.log("boolean "+matched+" and index "+index);
我明白了:
matched: false index: 0
matched: false index: 1
matched: true index 2 //it should have stopped here since matched = true
matched false index 3 // this should NOT have printed
所以突破没有任何想法?
【问题讨论】:
-
return (String(foundItemKey).trim() === String(key).trim());应该工作。
标签: selenium protractor browser-automation e2e-testing webautomation