Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data displaying in a table <td> in Cypress.io test?

In a Cypress.io test, while checking for the 'data' displayed in a table after applying the filter, it throws "CypressError: Timed out retrying: Cannot read property 'eq' of undefined". Can someone please advise how to fix the problem in below test? Table HTML image added below.

describe('Filter Test', function() {
    it.only('Check if the records are filtered successfully', function() {
        cy.visit('http://www.seleniumeasy.com/test/table-search-filter-demo.html')          
        cy.get('button').contains('Filter').click()
        cy.get('input[placeholder="Username"]').type('jacobs')  
        cy.get('table').should(($tr) => {
        const $tds = $tr.find('td') // find all the tds
        expect($tds.cells.eq(0)).to.contain('jacobs')   
        })

    })      

})

enter image description here

enter image description here

like image 676
soccerway Avatar asked Aug 16 '18 10:08

soccerway


People also ask

How do I get an element's text contents in Cypress?

How do I get an element's text contents? Cypress commands yield jQuery objects, so you can call methods on them. If the text contains a non-breaking space entity &nbsp; then use the Unicode character \u00a0 instead of &nbsp; . Tip: watch the Confirming the text with non breaking space entity video.

How do I get text from a locator in Cypress?

Cypress can validate the text on an element with the help of jQuery text() method. This method shall help us to fetch the text content on the selected element. We can also put assertions on the text content of the element. cy.

How do you know if an element is present in Cypress?

Subsequently, you can query the element within the body using the “find” method, the element's ID or class and a callback function. If the element exists, the callback function will return true. If the element does not exist, the callback function will return false.


1 Answers

There are multiple ways to do this, but the contains() function is by far the simplest in this case:

cy.get('table').contains('td', 'jacobs');

This will get the table element and assert that it contains a td tag with the text jacobs.


It's worth noting that contains() also acts as a selector, and in typical Cypress fashion you can continue chaining off it, like so:

cy.get('table').contains('td', 'jacobs').should('be.visible');

cy.get('table').contains('td', 'jacobs').then(elem => {
    // Do something with this specific element...
});

// etc...
like image 129
Joshua Wade Avatar answered Sep 22 '22 03:09

Joshua Wade