Search code examples
javascriptxpathcypress

Find one of two elements without fail in Cypress


I am doing automation testing using Cypress with Javascript.

Question/Issue

I have one scenario in which one of two elements should be available on the screen. Is it possible to handle this scenario?

Description

Inside kebab menu, multiple options are available and I have to check that required options should be visible. One of them is 'Set active'/Set inactive'. If the element is active, menu displays 'Set inactive' and vice-versa. Now I want to check that 'Set active/Set inactive' should be visible. For that I used cy.xpath('//p[normalize-space()="Set active"]').should('be.visible') and cy.xpath('//p[normalize-space()="Set inactive"]').should('be.visible'). But it fails if one of them not found. I also found that cypress not allowed try-catch.

How to handle this scenario?

I didn't find anything which is helpful.

Please help me. Thanks!


Solution

  • One option for selecting either/or element is Multiple Selector (“selector1, selector2, selectorN”).

    Cypress have archived their xpath library, so you may wish to convert to CSS selectors.

    The following should be the CSS selectors equivalent to the xpath. The comma between expression means take either/or element.

    cy.get('p:contains("Set active"), p:contains("Set inactive")')
    

    My xpath is a bit rusty, I'm assuming p[normalize-space()="Set active"] means something like

    get the <p> element which has trimmed text of "Set active"


    If you want to continue using xpath, there is the | operator that would do the same job as Multiple Selector.

    cy.xpath('//p[normalize-space()="Set active"] | //p[normalize-space()="Set inactive"]')