简体   繁体   中英

How to get all elements until there isn't any element in cypress

A have a command in my cypress project, in which is supposed to delete all registries of a certain entity (files) from user's account, and it runs before each test.

It's main step runs like following:

  • Awaits page finish loading
  • Click on each delete button.
  • A modal with a text will shows up.
  • Copy the delete text in it.
  • Paste on the input.
  • Click on delete button.
  • Query DOM for a text that only shows up when all entries are deleted.
  // Await loading
  cy.contains('Carregando...').should('not.be.visible')

  // Find all delete buttons by its svg path
  cy.get(
    `[d='M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z']`,
  )
    .parent()
    .parent()
    .parent()
    .each((delete_button, index, list) => {
      cy.wrap(delete_button).click({ force: true })
      // Fills in modal using the correct deletion phrase.
      cy.contains(/^Escreva "(.*)" para confirmar/).then(el => {
        const reg = RegExp(/^Escreva "(.*)" para confirmar/)
        const confirmation = reg.exec(el[0].innerText)[1]

        cy.get(`[placeholder='${confirmation}']`).type(`${confirmation}{enter}`)
      })
      cy.contains('Carregando...', { timeout: 60000 }).should('not.be.visible')
    })

  // Asserts that table section is all clear
  cy.get('span').should(
    'contains.text',
    'Ao inserir uma tabela no sistema você poderá criar fluxos e treinar seus modelos a partir da sua base de dados.',
  )

On the first test, since the project has some entries, this commands pass normally, but in the following test it will fail, because the get command doesn't find any svg as reference to find the button on screen.

How can I change this command, so it can pass on both cases when :

  • It delete all existing entries on screen.
  • All entries have already been deleted, it should pass too.

It looks like you need to check element existence first?

cy.get('body').then(($body) => {
  if ($body.find('[d=...]').length) {
    // svg was found, find the buttons
    cy.get('[d=...]')
    ...the rest of your code...
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM