DEV Community

loading...

.innerText vs. .textContent in Cypress

Sergey Blohin
QA, Ruby, JS
・1 min read

When we use the have.text assertion, we expect the validation to be full-text, by .innerText.

cy
  .get('div')
  .should('have.text', 'foo');
Enter fullscreen mode Exit fullscreen mode

But Cypress have.text returns .textContent.
This behaviour can cause unexpected results.
For example, your HTML code may have the following code:

<div>foo<span style="display: none;">bar</span></div>
Enter fullscreen mode Exit fullscreen mode

The browser will only show foo.
Also, document.querySelector('div').innerText will only show foo.

> $0
< <h1>​"foo"<span style=​"display:​ none;​">​bar​</span>​</h1>​
> $0.innerText
< "foo"
> $0.textContent
< "foobar"
Enter fullscreen mode Exit fullscreen mode

Alt Text

Cypress use MochaJS => Chai => Chai-jQuery => jQuery.

github.com/jquery/jquery/src/core.js#L276

// Retrieve the text value of an array of DOM nodes
    text: function( elem ) {
        var node,
            ret = "",
            i = 0,
            nodeType = elem.nodeType;

        if ( !nodeType ) {

            // If no nodeType, this is expected to be an array
            while ( ( node = elem[ i++ ] ) ) {

                // Do not traverse comment nodes
                ret += jQuery.text( node );
            }
        } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
            return elem.textContent;
        } else if ( nodeType === 3 || nodeType === 4 ) {
            return elem.nodeValue;
        }

        // Do not include comment or processing instruction nodes

        return ret;
    },
Enter fullscreen mode Exit fullscreen mode

Discussion (0)