Cypress is capable of handling web tables. A table is basically of two types, which are dynamic and static. A static table has a fixed number of columns and rows, unlike a dynamic table.
In an Html code, a table is represented by table tag name, while rows are represented by tr and columns by td.
- To access the rows, the Cypress command is as follows −
cy.get("tr")
- To access the columns, the Cypress command is as follows −
cy.get("td") or cy.get("tr td")
- To access a particular column, the CSS expression should be as follows −
td:nth-child(column number)
- To iterate through the rows/columns of the table, the Cypress command each is used.
In Cypress, we have the command next to shift to the immediate following sibling element. This command has to be chained with getting command. The command prev is used to shift to the immediate preceding sibling element.
The Html structure of a table is given below −
Example
Let us take an example of a table, and verify the content of the second column TYPE (Open Source) corresponding to the value Selenium, which is in the first column AUTOMATION TOOL.
The following screen will appear on your computer −
Implementation
Given below is the implementation of the Cypress commands related to tables −
describe('Adglob Test', function () {
// test case
it('Scenario 1', function (){
//URL launch
cy.visit("https://sqengineer.com/practice-sites/practice-tables-selenium/")
// identify first column
cy.get('#table1> tbody > tr > td:nth-child(1)').each(($elm, index, $list)=> {
// text captured from column1
const t = $elm.text();
// matching criteria
if (t.includes('Selenium')){
// next sibling captured
cy.get('#table1 > tbody > tr > td:nth-child(1)')
.eq(index).next().then(function(d) {
// text of following sibling
const r = d.text()
//assertion
expect(r).to.contains('Commercial');
})
}
})
});
});
The execution logs show that the value in the column TYPE is captured as Open Source. This happens as it is the immediate following sibling to the element Selenium (first column)which appears in the same row.
Thanks for sharing, this is a fantastic article.Thanks Again. Much obliged.
Major thankies for the blog article.Much thanks again. Awesome.