當getText失敗時如何從元素獲取文本


0

我有以下內容

element(by.css("span[aria-label='Picker ID, TESTUSER']")

我想確保此字段上的文本為TESTUSER,所以我嘗試:

 expect(element(by.css("span[aria-label='Picker ID, TESTUSER']")).getAttribute('value')).toEqual('TESTUSER');

然後我得到了錯誤:Expected null to equal 'TESTUSER'

所以我嘗試了:

element(by.css("span[aria-label='Picker ID, TESTUSER']")).getText().then(function (value) {
        console.log(value);
      })

我得到了這個錯誤:

Expected '' to be 'TESTUSER'.

如何獲取此字段的值並期望它是TESTUSER?

1

So in most cases try in the following order:

getText() if it doesn't work use getAttribute('textContent') if that too doesn't work use getAttribute('value')

getAttribute('value') works only if there is an attribute called value in your element (like id, name etc)

So in most cases, if getText doesn't work use .getAttribute('textContent') Use:

element(by.css("span[aria-label='Picker ID, TESTUSER']")).getAttribute('textContent')

Because getText or text() actually uses innerText ,and will not detect text from hidden elements .

Don't get confused by the differences between Node.textContent and HTMLElement.innerText. Although the names seem similar, there are important differences:

textContent gets the content of all elements, including and elements. In contrast, innerText only shows “human-readable” elements.

textContent returns every element in the node. In contrast, innerText is aware of styling and won’t return the text of “hidden” elements.

Moreover, since innerText takes CSS styles into account, reading the value of innerText triggers a reflow to ensure up-to-date computed styles. (Reflows can be computationally expensive, and thus should be avoided when possible.)

Unlike textContent, altering innerText in Internet Explorer (version 11 and below) removes child nodes from the element and permanently destroys all descendant text nodes. It is impossible to insert the nodes again into any other element or the same element after doing so

https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent