Home > Blockchain >  issue with recursive function in cypress typescript
issue with recursive function in cypress typescript

Time:08-17

I have a table that has 'add' and 'remove' buttons underneath to add and delete columns. if a column is added to the table the remove button is enabled. However, if i were to remove all the added columns the remove button would be disabled (quite understandably as there are no columns to delete). I have written a recursive function that checks any added columns and then deletes them. The issue is it deletes all but still attempts to click the delete button. i think the issue lies in this if function-

if (element.find('disabled').length === 0) {
                this.deleteNonDefaultStopZones();
              }

Any help is greatly appreciated!

  public deleteNonDefaultStopZones(): SettingsPage {
    cy.get('[aria-label="Remove zone price"]').then((element) => {
      if (element.find('disabled').length > 0) {
        return this;
      }
      cy.get('[aria-label="Remove zone price"]')
        .click()
        .then((element) => {
          if (element.find('disabled').length === 0) {
            this.deleteNonDefaultStopZones();
          }
        });
    });
   
    return this;
  }

CodePudding user response:

To delete any existing rows, you can use .each() to click the remove button as many times as they are rows.

cy.get('.row-selector')
  .each( () => {
    cy.get('[aria-label="Remove zone price"]')
      // you may want to additional check base on how your app handles removing a row
      .should('be.visible')
      .click()
  })

CodePudding user response:

The basic problem is the exit test for the recursion isn't correct.

Instead of this

if (element.find('disabled').length > 0) {
  return this;
}

use this

if (element.attr('disabled')) {
  return this;
}

The .find() method is looking for a descendent element with tag <disabled>, and it never finds it so the recursion never exits properly.

You might also want to add an attempts counter to block infinite recursion.

public deleteNonDefaultStopZones(attempts = 0): SettingsPage {
  if (attempts > 1000) throw 'Too many attempts'
  ...

The upper limit of attempts will depend on how slow the DOM changes after .click() triggers column removal.

You may also want to .wait(...) before the next recursion

cy.get('[aria-label="Remove zone price"]')
  .click()
  .wait(1000)
  .then(() => this.deleteNonDefaultStopZones())  // no need to test disabled here
  • Related