Estoy tratando de itirar a través de una lista de enlaces en una tabla y asegurarme de que la página siguiente tenga la URL correcta pero tengo problemas. Un problema es que no hay buenos nombres de clase con los que trabajar, así que he estado usando cy.xpath.
//Loop through each element (This is a dynamic amount of elements) cy.xpath('//span[text()="Id"]//following::a[contains(@href,"maps")]'.each($el) => { cy.get($el).then(($btn) => { let id_text = $btn.text() //Check that the element is visible and click on it cy.get($el) .should('be.visible') .click() //Check that the url contains the text value of the element that was clicked on cy.url() .should('contain', id_text) }) })Funciona una vez y luego se tropieza diciendo que el elemento DOM se separó
Puedes acortar tu código así:
cy.get('[href*="maps"]').each(($el) => { let id_text = $el.text().trim() //Check that the element is visible and click on it cy.wrap($el).should('be.visible').click() //Check that the url contains the text value of the element that was clicked on cy.url().should('contain', id_text) //Wait half a sec cy.wait(500) })Cuando ve que el elemento DOM se separó , significa que una acción ha hecho que la página se actualice y una consulta anterior ya no apunta a un elemento válido.
En su caso, la acción es .click() y la lista de elementos seleccionados por cy.xpath('//span[text()="Id"]//following::a[contains(@href,"maps")]') se ha actualizado, por lo que la lista que Cypress está iterando ya no es válida.
Un enfoque para resolver esto es separar la prueba en dos bucles.
const links = []; // save link info here const selector = '//span[text()="Id"]//following::a[contains(@href,"maps")]'; cy.xpath(selector) .each(($el, index) => { const id_text = $el.text() links.push(id_text) cy.xpath(selector).eq(index) .as(`maps${index}`) // save a unique alias for this link }) cy.then(function() { links.forEach((link, index) => { // Check that the element is visible and click on it cy.get(`@maps${index}`) // get the element from the alias .should('be.visible') .click() //Check that the url contains the text value of the element that was clicked on cy.url().should('contain', link) cy.go('back') // return to start page }) })