Ara Galstyan
Ara Galstyan

Reputation: 556

How to use logical OR in Cypress should assertion

I have this code

cy.get(element).should('contain.text', search_word || search_word.toLowerCase())

And I get this error

expected <div.games__element__title.card-title.h5> to contain text Hot, but the text was Ultimate hot

How can I use OR operator, so I can assert that the text of element contains the searching word written either in uppercase or in lowercase letters?

Upvotes: 16

Views: 14265

Answers (2)

deerawan
deerawan

Reputation: 8443

For text comparison, instead of using OR approach, I suggest using lowercase comparison by having the expected text and actual text to be compared in the lowercase version. This is a cleaner approach.

cy.get(element).invoke('text').should(text => {
  expect(text.toLowerCase()).to.contain(search_word.toLowerCase());
})

another alternative is using regex

cy.get(element).invoke('text').should('match', /(h|H)ot/);

Upvotes: 5

Alapan Das
Alapan Das

Reputation: 18634

One way to achieve what you are looking for, is by using the Conditional statement in cypress. We will get the inner Text from the element and then check whether the word hot or Hot is present in the text and based on that we will perform actions.

cy.get(element).invoke('text').then((text) => {
   if (text.includes('Hot')) {
      //Do Something
   }
   else if (text.includes('hot')) {
      //Do Something
   }
   else {
      //Do Something
   }
})

Upvotes: 3

Related Questions