javascriptcypresscypress-custom-commandscypress-conditional-testing

I am facing a problem to verify element visibility if element in visible or not using cypress


When I try

cy.get('div.userId')

I want to add condition div.userId is exists/not in dom.

I am expecting not to fail test before checking existence of element in dom.

Like sometimes div.userId is not visible and cy.get(div.userId) fails but we ma need to click another element to make it visible. simple wanna use if-else statement upon this...


Solution

  • @MadhuriVarada is correct, but the other answer is misleading you. It is possible and often required to test for an element that exists or not.

    You can easily do it with cypress-if plugin commands

    Easy conditional if-else logic for your Cypress tests

    Please review the videos and blogs in the above link for better information, especially the Cypress Flakiness Example

      cy.get('[data-cy=customer-item]')
        // the elements are there, the list will not change
        // thus we can set the timeout to 0
        // to quickly move to the next steps
        .not('[data-status=active]', { timeout: 0 })
        .if('exists')
        .sample()
        .click()
        .then(() => {
          // find the button that contains the text "Activate Subscription"
          // and click on it
          cy.contains('Activate Subscription').click()
          // the page should contain a visible element
          // with text "Subscription was activated"
          cy.contains('Subscription was activated').should('be.visible')
        })
        .else('Could not find inactive subscription')
    

    This way you avoid using jQuery expressions that could end up as flaky test, since jQuery does not wait for asynchronous loaded elements.