DEV Community

Sergey Blohin
Sergey Blohin

Posted on

5 4 1 1 1

.innerText vs. .textContent in Cypress

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (2)

Collapse
 
dvpita profile image
Jose Pita

do u have any workaround to compare text?

Collapse
 
georgeruban profile image
GeorgeRuban

docs.cypress.io/faq/questions/usin... says

cy.get('div').should(($div) => {
// access the native DOM element
expect($div.get(0).innerText).to.eq('foobarbaz')
})

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay