Tutorial 9 – Handle HTML Webtable in Cypress
What you will Learn :
Pick any value from table and verify the value
Pick a value from specific row and column in a table and verify
SCENARIO 1: Pick any value from table and verify the value
Launch http://testautomationpractice.blogspot.com/ and come to be page bottom, you would see an HTML table containing data.
We would like to pick any value from this table and want to verify the value. So, let us say, we would like to check the value ‘Javascript’ anywhere in the table. This value might be present anywhere in the table.
We will begin by inspecting the table
Hover the mouse over <table name=”BookTable”>
You would see that entire table gets highlighted
Next open chropath & click ‘Selectors’ dropdown
Select ‘Css Sel..’ from dropdown. In the field, type table[name=BookTable] and hit Enter. You would see that the entire table gets highlighted (seen enclosed in dotted rectangle)
Create a new .spec.js script
Launch site and get the table
Next let us inspect the data inside the table viz ‘Javascript’, you would notice that this value is part of ‘td’ tag
So we can use the contains() method that accepts 2 arguments: first one is ‘td’ and second one is the data value from table (here ‘Javascript’). You can double click ‘Javascript’ value that you see in the ‘td’ tag (seen above), copy it and paste in 2nd argument.
So we are locating a table in which there is some ‘td’ tag that contains the data ‘Javascript’.
Save the code.
Let us open the test runner & execute this much code. Notice that the test gets passed
SCENARIO 2: Verify some value in specific row and column
Rows are represented by ‘tr’ tag and column by ‘td’ tag.
Let’s say we want to read the value from 4th row & 4th column viz the value 300
To do that, inspect 300
Next ‘Copy selector’ to automatically generate css selector
Paste it in code editor (line 10)
The below portion of line 10 represents our table
So this portion can be replaced by
So we now have line 10 simplified
Next, under the table tag we have body and under the body tag we have various rows (represented by tr). The tr tag contains data represented by td tag.
The nth-child will help us identify the row and column number. So, in this case, the number 4 represents 4th row and 4th column. So in line 10 we are getting the 4th row and 4th column and verifying if it contains 300
Save the code, notice beloe the test is pass
Let us change 300 to some other value
Save the file, notice below that assertion fails this time
So this is how we can extract values from a simple HTML web table.
Thanks ro reading!