Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we test if element text includes text_ A or text_B with cypress?

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
     }
 });
like image 791
KoKa Avatar asked Oct 08 '19 13:10

KoKa


People also ask

How do I get an element's text contents in Cypress?

How do I get an element's text contents? Cypress commands yield jQuery objects, so you can call methods on them. If the text contains a non-breaking space entity   then use the Unicode character \u00a0 instead of   .

How do you verify text in Cypress?

Cypress can validate the text on an element with the help of jQuery text() method. This method shall help us to fetch the text content on the selected element. We can also put assertions on the text content of the element. cy.

How do you know if an element is present or not in Cypress?

Conditionally check whether an element has certain text: get('body'). then(($body) => { // synchronously ask for the body's text // and do something based on whether it includes // another string if ($body. text(). includes('some string')) { // yup found it cy.

How do you use contain in Cypress?

contains() is chained off of a command that yielded the <button> , Cypress will look inside of the <button> for the new content. In other words, Cypress will look inside of the <button> containing "Delete User" for the content: "Yes, Delete!", which is not what we intended.


2 Answers

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

like image 192
Cory Danielson Avatar answered Sep 30 '22 03:09

Cory Danielson


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));
 });
like image 40
Lovenkrands Avatar answered Sep 30 '22 03:09

Lovenkrands