https://cypress.io logo
Verifying if a value is present or not, in a table...
# i-need-help
q
Hi, I have a scenario where I add a value to a table with multiple rows and columns. I need to iterate through the table and find the value, if its present then print its location or a success message. And if the value is not found then fail the test. How can I do this efficiently? Can someone help?
cy.get('row selector').each(($rows, $index) => { const row = $rows.text() if (row .includes('desired value')) { cy.get('row selector').eq($index) } })
This is the logic am currently using. I am not sure what my else statement would be to fail the test.
g
you just want to print the row index?
t
try something like this: cy.get('table') //selects the table .find('tr') //finds the lines .each(($row, rowIndex) => { //for each row cy.wrap($row) //select the row .find('td') //finds the cells .each(($cell, cellIndex) => { //for each cell const cellText = $cell.text() //gets cell text if (cellText.includes('value looked for')) { //if the value is found cy.log(
Value found in row ${rowIndex + 1}, column ${cellIndex + 1}
) //prints location return false //stop the loop } }) .should('not.be.empty') //make sure the line is not empty }) .should('not.be.empty') //make sure the table is not empty .should('exist') //ensures that the table exists .then(() => { //when the search is complete cy.log('Value not found') //prints error message expect(false).to.be.true //test failed })
q
Yes. Just the location of the element, if found. The problem I have currently is that if the element is not found, the test still passes.
Great! Will try this. Thank you 😀
This is not working for me. It successfully executes "if" condition and prints the location, but also throws assertion error
cy.get('selector').each(($rows, $index) => { const value = $rows.text() cy.log(value) if (value.includes('desired value')) { cy.log(
Value found in row ${$index + 1}
) return false } }).then(() => { cy.log('Value not found') expect(false).to.be.true })
Am I missing something?

https://cdn.discordapp.com/attachments/1104259979269120080/1104998452913504326/image.pngâ–¾

*Never mind. I figured it out. Added a flag. * let flag=0 cy.get('selector').each(($rows, $index) => { const value = $rows.text() cy.log(value) if (value.includes('desired value')) { cy.log('Value found in row ${$index + 1} ') flag=1 } }).then(() => { expect(flag).to.equal(1) })
g
q
Thanks for this simple solution @gray-kilobyte-89541. Really appreciate it 😃
6 Views