【问题标题】:why locator() in Protractor?为什么在量角器中使用 locator()?
【发布时间】:2016-12-26 11:47:28
【问题描述】:

来源: http://www.protractortest.org/#/api?view=ElementArrayFinder.prototype.locator

// returns by.css('#ID1')
$('#ID1').locator()

// returns by.css('#ID2')
$('#ID1').$('#ID2').locator()

// returns by.css('#ID1')
$$('#ID1').filter(filterFn).get(0).click().locator()

我相信,不包括 locator() 也可以精确地完成同样的工作;此 API 的任何原因或具体原因?

【问题讨论】:

    标签: selenium selenium-webdriver protractor


    【解决方案1】:

    就我个人而言,我只是用它来更好地记录错误。即

    it('should display the facility name', function () {
        var el = element(by.css('div.facilityName'));
        expect(el.isDisplayed()).toBe(true, 'Expected element ' + el.locator() + ' to be present and visible';
    });
    

    这会在我的控制台中返回:

    失败:

    1) 应显示设施名称

    预期 false 为真,“预期 By(css selector, div.facilityName) 存在且可见”。

    同样,我将它与一些辅助函数一起使用(我在非 Angular 上使用 Protractor,所以我没有等待 Angular 同步可用的能力,所以我使用如下帮助函数:

    /**
    * @description Prevents test execution until the given element is present in the DOM
    * @param [el] The element locator [time] The optional max timeout in ms [opts] The options
    */
    Util.prototype.waitForElementPresent = function (el, time, opts) {
        var timeout = time || 0,
        counter = 0,
        verbose = opts ? opts.verbose : false;
    
        return browser.wait(function() {
            if (verbose) {
                process.stdout.write( !counter ? 'waitForElementPresent [' + el.locator() + '] ' : '.');
                counter = counter + 1;
            }
            return el.isPresent();
        }, timeout).then(function () {
            if (verbose) {
                process.stdout.write('\n');
            }
        });
    };
    

    用法:

    it('should display the facility name', function () {
        var el = element(by.css('div.facilityName'));
        Util.waitForPresentAndVisible(el, 10000, {verbose: true});
        expect(el.isDisplayed()).toBe(true, 'Expected element ' + el.locator() + ' to be present and visible';
    });
    

    这会打印到控制台:

    waitForElementPresent [By(css selector, div.facilityName)]..........

    这有点微不足道,因为无论如何错误都会包括失败代码的行和索引。但我发现在某些情况下它有助于改进错误记录。

    我很好奇其他人如何使用它。

    【讨论】:

    • 有趣的用例!再发一篇。
    【解决方案2】:

    locator() 在现实世界中没有太多用处,但这里还有一个用例 - avoid using by.xpath() in solving the "getting direct child of a current element" problem with CSS selectors 通过获取父元素的定位器并将其与直接子元素连接以动态生成完整的 CSS选择器。

    【讨论】:

    • 当然,我们需要连接;量角器文档落后于stackoverflow :)
    猜你喜欢
    • 2020-10-15
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 2012-03-17
    相关资源
    最近更新 更多