skip to Main Content

I need to check if the input element has one of 3 values as I am automating AI feautre and it sometimes generates random text, but still uses at least one value.

So I need to check if input has A or B or C value, one of this values

How can I do this?

Tried this from one of questions here –

cy.get('section div:nth-child(4)').invoke('text').then((text) => {
 expect(text).not.equal(companyNameText);
 expect(text).not.equal(descriptionText);
 expect(text).not.equal(purposeText);
})

Does not work in my case

2

Answers


  1. You an use Chai’s oneOf method to achieve this. There is a caveat from the docs:

    Asserts that the target is a member of the given array list. However, it’s often best to assert that the target is equal to its expected value.

    cy.get('section div:nth-child(4)').invoke('text').then((text) => {
      expect(text).to.be.oneOf(
        [companyNameText, descriptionText, purposeText]
      );
    });
    
    Login or Signup to reply.
  2. You are testing using expect(...).not.equal(...) on all three strings, which results in the opposite test.

    Instead you can use string comparison and OR operator,

    cy.get('section div:nth-child(4)').invoke('text').then((text) => {
      const matches = (text === companyNameText) ||
        (text === descriptionText) ||
        (text === purposeText);
      expect(matches).to.eq(true)
    })
    

    Another way is Array.includes

    cy.get('section div:nth-child(4)').invoke('text').then((text) => {
      const validStrings = [companyNameText, descriptionText, purposeText]
      const matches = validStrings.includes(text)
      expect(matches).to.eq(true)
    })
    

    or a variation with .to.include() matcher

    cy.get('section div:nth-child(4)').invoke('text').then((text) => {
      const validStrings = [companyNameText, descriptionText, purposeText]
      expect(validStrings ).to.include(text)
    })
    

    Even more, it’s possible to use cy.contains() with a RegExp that has OR operator built in

    const regex = new RegExp(`${companyNameText}|${descriptionText}|${purposeText}`);
    cy.contains('section div:nth-child(4)', regex)
    

    Another one, with .should()

    cy.get('section div:nth-child(4)')
      .should('have.any.text', (companyNameText, descriptionText, purposeText))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search