When we use the have.text
assertion, we expect the validation to be full-text, by .innerText
.
cy
.get('div')
.should('have.text', 'foo');
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>
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"
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;
},
Top comments (2)
do u have any workaround to compare text?
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')
})