'Cypress: How to check if the element has a cropped text by text-overflow?
Is there a way to check if text was cropped by text-overflow?
CSS:
.elem {
...
overflow: hidden;
text-overflow: ellipsis;
...
}
Sometimes element contain many text which overflowed and it's ending replace with '...'.
This won't work because actually there no '...' in element content it only visual:
cy.get(elem).should('contain', '...')
Solution 1:[1]
Ellipsis display depends on the element width.
Given this HTML
<style>
div {
width: '30px';
overflow: hidden;
text-overflow: ellipsis;
}
</style>
<div>Really long textttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt</div>
this will test the ellipsis at specified widths.
Testing the width is as expected will make a stronger test.
cy.get('div').then($div => {
expect($div.css('width').replace('px', '') - 30).to.be.lt(1) // approx
})
cy.get('div').then($div => {
const offsetWidth = $div[0].offsetWidth
const scrollWidth = $div[0].scrollWidth
const isEllipsisActive = offsetWidth < scrollWidth
expect(isEllipsisActive).to.eq(true) // ? passes
})
cy.get('div').invoke('css', 'width', '500px') // widen the element
cy.get('div').then($div => {
expect($div.css('width').replace('px', '') - 500).to.be.lt(1) // approx
})
cy.get('div').then($div => {
const offsetWidth = $div[0].offsetWidth
const scrollWidth = $div[0].scrollWidth
const isEllipsisActive = offsetWidth < scrollWidth
expect(isEllipsisActive).to.eq(false) // ? passes
})
Solution 2:[2]
You can make CSS assertions to check the element has text-overflow.
cy.get(elem).should('have.css', 'text-overflow', 'ellipsis')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | jjhelguero |
