I'm a new developer and I am trying to build a certain test using cypress. the client has a dynamic grid, and I'd like to see which row in the grid contains the data I want. I cannot change the HTML file.
At the moment I am trying to iterate over all rows using each() cypress command. So I have two questions:
thanks!
Using each is a pretty good approach, select the rows and make use of the index parameter to find which one.
cy.get('[role="row"]').each(($row, index) => {
if ($row.find('span').text() === 'aaaa') {
cy.wrap(index).as('rowIndex')
})
cy.get('@rowIndex')
.then(rowIndex => {
// use the row index here
})
There's also this method Cypress get index of th element to use it later.
If it works (the jQuery docs don't show this usage) the code for your HTML would be
cy.contains('[role="row"]', 'aaaa').invoke('index').as('rowIndex')
cy.get('@rowIndex')
.then(rowIndex => {
// use the row index here
})
I have a test doing the same thing and the way I've approached it was:
cy.contains('aaaa').invoke("text").as('variableName')
This can now be used like this:
cy.get(this.variableName).should('be.visible')
cy.contains('aaaa').parent().next().children() //Used to iterate through rows.
There are a number of approaches you can take, but I think my preferred one is to store the variable in Cypress environment variable. In the following, I get the element, then use a .then() statement to get the text of the element (with the JQuery function, .text()), and store it in a Cypress environment variable (via Cypress.env()).
describe('tests', () => {
it('test', () => {
cy.get('some-element').then(($el) => {
Cypress.env('myVar', $el.text());
})
... // some code
// When needing the variable, reference it by Cypress.env('myVar');
});
afterEach(() => {
// after each test, clear the variable
Cypress.env('myVar', null)
});
});