Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a cypress command if content is present and skip if content is not present

Hi I am working with cypress for UI testing. Based on user we do have additional button on the page.

Is there a way cypress can look for a button and run the commands if button is present and skip the command if button is absent thus preventing from element not found error.

<div class="btn btn-success" id="editButton">Edit</div>

Cypress code is

    if (!cy.get('div[id=editButton]')) {
        this.skip();
    } else {
        cy.get('div[id=editButton]').click();
    }
   

And yet cypress throws element not found error.

like image 837
MPK Avatar asked Oct 28 '25 00:10

MPK


2 Answers

Perhaps use a variation of Dynamic Text test

cy.get('body').then(($body) => {

  const button = $body.find('div[id=editButton]')
  if (button.length) {
    // yup found it
    cy.get('div[id=editButton]').click()
  }

  // don't need this.skip()
})

Please see the caveats on that page about conditional testing. If your $body.find('div[id=editButton]') fails because the button has not appeared yet, you will need to add more assertions to the test.


Another approach is to test for different classes of user. This makes your test suite more complete

For example,

it('tests the admin user', () => {
  cy.login('admin')
  cy.get('div[id=editButton]').click()
  ...  
  callCommonUserTests()
})
it('tests the read-only user', () => {
  cy.login('read-only')
  // cy.get('div[id=editButton]').click()  // edit button not available
  ...  
  callCommonUserTests()
})

Now the test suite is much simpler and less prone to timing issues.

You can consolidate code common for all users in functions or custom commands.

like image 135
Fody Avatar answered Oct 29 '25 13:10

Fody


To use jQuery with Cypress.$ you can test the existence without failing the test

it('tests the edit button', () => {
  if (Cypress.$('#editButton').length) {
    cy.get('div[id=editButton]').click()
    // rest of test
  }
})

Or

it('tests the edit button', () => {

  if (!Cypress.$('#editButton').length) {
    this.skip()                              // exit the test here
  }

  cy.get('div[id=editButton]').click()
  // rest of test
})
like image 37
Seeker Avatar answered Oct 29 '25 14:10

Seeker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!