How to Assert from multiple possibilities in Cypress? One option could be true out of multiple

2.1k views Asked by At

I have a scenario, where i need to put Assertion on an element's text which could be true OR pass the test case, if the any 1 value is present out of many.

Let say, an element can contain multiple status' : 'Open', 'Create', 'In Progress' any of these could be true.

How can i implement this scenario and Assert with OR logical operator or any other way?

cy.get('element').should('have.text', 'Open' | 'Create')

3

There are 3 answers

0
Woden On BEST ANSWER

It sounds like a one-of assertion, something like the following:

cy.get('element')
  .invoke('text')
  .should('be.oneOf', ['Open', 'Create'])

To do it you need to extract the text before the assertion.

For reference see chaijs oneOf

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.

2
KyleFairns On

Wodens answer is most valuable if you wish to make an assertion and have the test fail if one of them doesn't exist

However, if you want to check the text of the element that is visible and do separate things based on which one is available:

cy
  .get('element')
  .filter(':visible')
  .invoke('text')
  .then((text) => {
       if(text.includes('Open')){
          // Things that only occur when Open is present
       } else if (text.includes('Create')){
          // Things that only occur when Create is present
       } else if (text.includes('In Progress')){
          // Things that only occur when In Progress is present
       } else {
         // Things that happen when the options are exhausted
       }
   });
0
Amit Verma On

These both Worked:

cy.get('element')
  .invoke('text')
  .should('satisfy', (text) => text === 'option1' || text === 'option2')

OR

cy.get('element')
  .invoke('text')
  .should('be.oneOf', ['option1', 'option2']);