gpt4 book ai didi

protractor - 使用 Protractor 搜索包含特定文本的转发器中的元素

转载 作者:行者123 更新时间:2023-12-04 12:47:33 26 4
gpt4 key购买 nike

如何从包含特定文本的转发器中搜索元素?

我试过这样的事情:

element(by.repeater('item in array')).all(by.cssContainingText('.xyz','my item title')); // only gets the first element

我可以使用 .then 自己搜索之后 element.all但我想知道它是否存在更简单的东西,比如 cssContainingText但对于中继器:
element(by.repeaterContainingText('item in array','my item title'))

或这样的元素链接:
element.all(by.repeater('item in array')).element(by.cssContainingText('.xyz','my item title'));

带过滤器的解决方案(但速度很慢)
element.all(by.repeater('item in array')).filter(function(elem){
return elem.getText().then(function(text){
return text.indexOf('my item title') > -1;
});
}).then(function(filteredElements) {
return filteredElements[0];
})

最佳答案

Protractor 允许添加定位器。我在一个有 20 个左右测试的项目中成功地使用了以下实现(纯 javascript)。

这是使用 lodash 和 jquery 的解决方案。
下面也有一个纯javascript。

https://gist.github.com/GuyMograbi/7a5f5e580bcf8d7da58a

by.addLocator('text',

/**
*
* @param {string} text - will be lowercased
* @param {string} selector - to get list of children
* @param {null|object} parent - protractor will provide this..
*/
function(text, selector, parent) {
return _.filter($(parent || 'body').find(selector), function(e){
return $(e).is(':visible') && $(e).text().toLowerCase().trim() === text.toLowerCase().trim();
});
});

并使用它
return $('table').all(by.text('my text', 'tr')).first().getText().then(function(text){...})

或者
return element(by.text('my text', 'tr')).getText().then(function(text){...})

不要忘记以下关于 Protractor 和定位器的内容

我只花了 2 个小时就想知道为什么我的定位器不起作用。请记住以下几点:
  • Protractor “忽略”隐藏元素,但是您的定位器默认情况下不会这样做..所以如果您编写自定义定位器,为了使其按预期的角度工作,您必须过滤掉隐藏元素
  • 如果您需要调试,我发现使用 getOuterHtml().then..
  • 最有用

    纯 JavaScript

    这就是没有 jquery 和 lodash 的情况
    by.addLocator('text',

    /**
    *
    * @param text - will be lowercased
    * @param selector - to get list of children
    * @param parent - protractor will provide this..
    */
    function(text, selector, _parent) {

    return Array.prototype.filter.call( (_parent || document).querySelectorAll(selector), function(e){
    return e && !!(e.offsetWidth || e.offsetHeight || e.getClientRects().length) && e.textContent && e.textContent.toLowerCase().trim() === text.toLowerCase().trim();

    });
    });
  • isVisible 部分最终取自 jquery 源。见答案:https://stackoverflow.com/a/33456469/1068746

  • 重要说明 - 或 - 为什么这应该是正确答案

    使用 filter 你会得到一个 promise 。使用此解决方案,您将获得一个元素。因此,您将拥有 getByText(..).then(function(e){ e.click() }),而不是 getByText(...).click() - 太棒了!

    限制和可能的增强

    在您的情况下,不能使用中继器定位器,这是一个无赖,除非您将位置而不是 text 修改为 textInRepeater,然后以某种方式在代码中添加 '[ng-repeat=' + repeater + ']'

    您可能想要增强的另一件事非常有用。
    有时您想获取一个包含文本的元素,或者可能包含一个带有文本的子元素,但您实际上想要选择父元素。

    关于protractor - 使用 Protractor 搜索包含特定文本的转发器中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25041023/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com