10

Just wondering if there is a way to test that an element contains text_A or text_B with cypress. For example, I have an element that is filled with the error returned from an API request and I want to check whether the error message includes text_A or text_B. Tried the following code but it works only if text_A is present and fails when text_B is returned.I don't get any error for invalid syntax from cypress, any help would be appreciated.

 cy.get('body').then((body) => { 
     if (body.find('#request-error').length > 0) { 
         cy.get('#request-error').then((el)=> {
              assert.include(el.text(), ('text_A' || 'text_B')); 
         });
     } else {
         // DO SOMETHING ELSE
     }
 });
KoKa
  • 797
  • 1
  • 14
  • 31
  • Try `cy.get('#request-error').contains(/text_A|text_B/g)`, from this question [Cypress expect element to contain one string or another string](https://stackoverflow.com/questions/58176344/cypress-expect-element-to-contain-one-string-or-another-string) – Ackroydd Oct 09 '19 at 23:36
  • 1
    Hi @Ackroydd thanks for the answer. I managed to make it work using the idea described to the link you provided. ```const runout = ['text_A', 'text_B'] const regex = new RegExp(`${runout.join('|')}`) const text = el.text() expect(text).to.match(regex) ``` – KoKa Oct 10 '19 at 07:54
  • Just one additional thing, you're doing this within the `.then((el) => ...`. Did you try out `.contains(regex)`? I notice from your comment to Cory that there's a substring factor and was wondering if that scenario also works with the simpler `.contains(regex)`. – Ackroydd Oct 10 '19 at 19:56

2 Answers2

8

Essentially you have an array of possible error messages, so you can test if the element's text exists within that array.

expect(['text_A', 'text_B']).to.include(el.text())

Another option that reads better would be to use .oneOf

expect(el.text()).to.be.oneOf(['text_A', 'text_B']);

https://docs.cypress.io/guides/references/assertions.html#BDD-Assertions

Cory Danielson
  • 14,314
  • 3
  • 44
  • 51
  • Hi Cory, thank you for the answer. However I don't think that this solution can be applied to my case since I want the opposite; text_A or text_B should be included to el.text(). For example el.text() = 'foo text_A bar' or el.text() = 'foo text_B bar'. Tried to switch the arguments and wrote: expect(el.text()).to.include([text_A', 'text_B']) but it failed with error AssertionError: expected 'foo text_A bar' to include [ 'text_A', 'text_B' ] – KoKa Oct 10 '19 at 07:20
  • Ahhh I see. Glad to see that you were able to get help with your issue in the comments! – Cory Danielson Oct 10 '19 at 17:55
3

I am late but you can do it with satisfy:

 cy.get('.text-element').invoke('text').then(text => {
      expect(text).to.satisfy((mText: string) => possibleMatchesArray.includes(mText));
 });
Lovenkrands
  • 165
  • 1
  • 10