How can we compare multiple text in cypress (not wanted and wanted or)

1.4k views Asked by At

If I have an element having text 'xyzzy', but I wanted to check this against all these: 'par' or 'xyzzy' or 'arc', how we can do it?

I'm not able to get it with this:

.should('have.text','Ab demo 1').and('have.text','ab demo 2')

Can we replace 'and' with 'or'?

6

There are 6 answers

0
Fody On

Just add the word any and provide the list to match

cy.get('(//div[@class="xyz"]')
  .should('have.any.text', ('Ab demo 1', 'Ab demo 2'))
0
TesterDick On

Can be done in a .should() command with a callback function

const texts = ['par', 'xyzzy', 'arc']

cy.get('(//div[@class="xyz"]').eq(2)
  .should($el => {
    const text = $el.text()
    expect(texts.includes(text)).to.eq(true)
  })
2
Alapan Das On

You can use the cypress assertion to.be.oneOf and do that. Something like:

cy.get('selector').then(($ele) => {
  expect($ele.text().trim()).to.be.oneOf(['xyzzy', 'par', 'arc'])
})
0
SuchAnIgnorantThingToDo-UKR On

Can use satisfy assertion,

cy.get('(//div[@class="xyz"]')
  .invoke('text')
  .should('satisfy', (text) => text === 'par' || text === 'xyz' || text === 'arc')
0
Visal On

The oneOf assertion can go inside .should()

cy.get('(//div[@class="xyz"]')
  .invoke('text')
  .should('be.oneOf', ['par', 'xyzzy', 'arc']) 
0
Aladin Spaz On

A simple approach is to use the multiple selector with :contains() pseudo selector

cy.get(':contains("xyzzy"), :contains("par"), :contains("arc")')