Home > Blockchain >  Cypress: contains().click() with or statement
Cypress: contains().click() with or statement

Time:06-24

the problem is that the Docker image from Cypress sets the browser language to english and some elements on the page are translated to english. It looks like it's a bug in Cypress because the browser in the Docker image, regardless of the set language, translates certain texts into English. even if the set browser language is different.

my local browser language is different than the one in the docker image so some texts are different for me locally than in the dockerimage (english). now i have to build a workaround until cypress manages to fix the bug.

i want cypress to select an element which is selected by a logical or ( || ). However it doesn't work because cypress.contains() doesn't support this. For a better illustration here is a simple example of what I mean. Do you have an idea how to implement this?

const value1 = data.text_local_language
const value2 = data.text_english

         cy.get("element")
          .contains(value1 || value2)
          .click();

CodePudding user response:

There is the oneOf assertion if an exact match is is acceptable.

cy.get('element')
  .should('satisfy', ($el) => {
    expect($el.text()).to.be.oneOf([value1,value2])
  })
  .click()

CodePudding user response:

You can check the text contains either text inside a .then() command and assert it.

const thisText = 'this'
const thatText = 'that'

cy.get('element')
  .then($el => {
    const text =  $el.text()
    const thisOrThat = text.includes(thisText) || text.includes(thatText)
    expect(thisOrThat, `text contains ${thisText} or ${thatText}`).to.be.true
    cy.wrap($el).click()
  })

CodePudding user response:

You can use a regular expression in contains()

const value1 = data.text_local_language
const value2 = data.text_english

const regex = new RegExp(`${value1}|${value2}`)  // build regex from variables

cy.get("element")
  .contains(regex)
  .click();

The regular expression (inside the slashes) value1|value2 matches either value1 or value2 (or is denoted by the pipe-symbol |).

CodePudding user response:

You can use a regular expression (RegExp) inside contains().

To build a regex pattern from variables use the constructor new RegExp with a string expression.

const value1 = 'Hello'
const value2 = 'World'

/* using concatenation with plus operator */
cy.get("element").contains(new RegExp(value1   '|'   value2))

/* using Array.join() */
const elements = ['Fire', 'Air', 'Water'];
cy.get("element").contains(new RegExp(elements.join('|'))

/* using ES6 template literals */
cy.get("element").contains(new RegExp(`${value1}|${value2}`)
  • Related