我目前正在使用 protractor 创建框架。我试图使用Protractor API提供的cssContainingText定位器。但是,定位器未能给出invalidElement异常,这对我来说似乎很奇怪。

页面的HTML看起来像这样

     <tbody>
        <tr class="row2">
             <td class="action-checkbox">...</td>
             <th class="field-name">
                 <a href="some_link">someText</a>
             </th>
             <td class="field-slug">sometext</td>
        </tr>
        <tr class="row3">
             <td class="action-checkbox">...</td>
             <th class="field-name">
                 <a href="some_link">someOtherText</a>
             </th>
             <td class="field-slug">someothertext</td>
        </tr>
        <tr class="row4">...</tr>
             <td class="action-checkbox">...</td>
             <th class="field-name">
                 <a href="some_link">someThirdText</a>
             </th>
             <td class="field-slug">somethirdtext</td>
        </tr>

我试图通过以下定位符使用文本someText-
element(by.cssContainingText('.field-name','someText'));,它奇怪地给出了InvalidLocator异常。当我使用以下定位符element(by.cssContainingText('a','someText'))时,代码可以正常工作。

根据我从here的解释和Protractor实现的here的理解,cssContainingText首先使用CSS选择器查找所有元素,然后匹配所需的文本。

因此,对CSS选择器使用.field-name类名称,然后匹配所需的字符串,这对我来说似乎非常好。但是,这失败了,我无法理解。在此方面的投入将很有帮助。

最佳答案

您可以从API documentation of cssContainingText开始并查看GitHub中的代码。

归结为这种在 clientsidescripts.js 中搜索内容的方式:

var elementText = element.textContent || element.innerText || '';

if (elementText.indexOf(searchText) > -1) {
    matches.push(element);
}

由于indexOf()需要完全匹配,并且您的th元素既没有innerText也没有textContent(您的<a>标记具有),因此使用th元素不会得到结果。

至于textContentinnerText之间的区别,让我引用this answer in SOto this one as well

对于您的情况:
[textContent]
someText
[/textContent]
[innerText]someText[/innerText]

var properties = ['innerHTML', 'innerText', 'textContent', 'value'];

// Writes to textarea#output and console
function log(obj) {
  console.log(obj);
  var currValue = document.getElementById('output').value;
  document.getElementById('output').value = (currValue ? currValue + '\n' : '') + obj;
}

// Logs property as [propName]value[/propertyName]
function logProperty(obj, property) {
  var value = obj[property];
  log('[' + property + ']'  +  value + '[/' + property + ']');
}

// Main
log('=============== ' + properties.join(' ') + ' ===============');
for (var i = 0; i < properties.length; i++) {
  logProperty(document.getElementById('test'), properties[i]);
}
<div id="test">
  Warning: This element contains <code>code</code> and <strong>strong language</strong> and <a href="www.google.com">a Google link</a>.
</div>
<textarea id="output" rows="12" cols="80" style="font-family: monospace;"></textarea>

关于javascript - 了解 Protractor 中的cssContainingText定位器功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44292857/

10-09 15:02