量角器自定义定位器无法定位元素

Protractor custom locator fails to locate the element

本文关键字:定位 元素 自定义 定位器 量角器      更新时间:2023-09-26

我已经为元素添加了一个自定义数据属性,我需要使用量角器识别和交互。属性为data-test-id。我在conf.jsonPrepare回调中创建了一个自定义定位器来检测元素。在下面:

onPrepare: function () {
    by.addLocator('testId', function(value, parentElement) {
      parentElement = parentElement || document;
      var nodes = parentElement.querySelectorAll('[data-test-id]');
      return Array.prototype.filter.call(nodes, function(node) {
        return (node.getAttribute('[data-test-id]') === value);
      });
    });
  }

我的angular应用程序有一个h1,里面有文本Home。我给它添加了data-test-id属性:

<h1 data-test-id="test-element">Home</h1>

这是我的量角器测试:

. js :

describe('Navigate to the website.', function() {
    it('Should have the Heading as Home', function() {
        browser.get('http://localhost:8888/#/');
        browser.waitForAngular();
        var textValue = 'Home';
        var heading = element(by.testId('test-element'));
        expect(heading.getText()).toEqual(textValue);
    });
});

conf.js :

exports.config = {
  //directConnect: true,
  seleniumAddress: 'http://localhost:4444/wd/hub',
  // Capabilities to be passed to the webdriver instance.
  capabilities: {
    'browserName': 'chrome'
  },
  // Spec patterns are relative to the current working directly when
  // protractor is called.
  specs: ['test.js'],
  // Options to be passed to Jasmine-node.
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000
  },
  onPrepare: function () {
    by.addLocator('testId', function(value, parentElement) {
      parentElement = parentElement || document;
      var nodes = parentElement.querySelectorAll('[data-test-id]');
      return Array.prototype.filter.call(nodes, function(node) {
        return (node.getAttribute('[data-test-id]') === value);
      });
    });
  }
};

当我运行示例测试时,我得到以下错误:

1)导航到网站。标题应该是Home
信息:NoSuchElementError: using locator: by. testd ("test-element")没有找到元素

我做错了什么?我怎么能解决这个问题,并得到这个工作?

当您获得属性时,您应该要求data-test-id而不是[data-test-id]。似乎是复制粘贴错误。

替换:

return (node.getAttribute('[data-test-id]') === value);

:

return (node.getAttribute('data-test-id') === value);

我也面临同样的问题,下面的解决方案解决了我的问题:

by.addLocator('lid', function(value, parentElement) {
        var nodes;
        if(parentElement)
            nodes =  parentElement.querySelectorAll();
        else
            nodes = document.querySelectorAll('body *');

        return Array.prototype.filter.call(nodes, function(node) {
            if( node.hasAttribute("lid") && node.getAttribute('lid') === value)
                return node;
        });
    });

querySelectorAll()需要将输入作为'tag',如果没有发送parentelelement,那么它将查询'body'标签下的所有标签,否则将查询来自parentelelement的所有元素。然后循环遍历所有元素并检查属性'lid'是否存在。如果存在,验证值,如果值是期望值,则返回该元素