alfredopacino
alfredopacino

Reputation: 3241

Cypress boolean assertion

I have a table that shows the results of a query. I check the table contains result using this:

cy.get("table", {timeout: 60000}).find("tr[data-index]").should("have.length.gt", 1);

But since I have different data sources, I want to check for both cases at the same time: the case I get some results and the case I get 0 results. In the latter, I would check for the presence of a message "No results found". How can I do this "double" assertion?

Upvotes: 2

Views: 4161

Answers (2)

Richard Matsen
Richard Matsen

Reputation: 23483

Take a look at my answer here How to check that element has either of classes in Cypress (sorry it's a long one).

You can test multiple OR conditions with .should('statisfy', callback).

Presuming the test should pass if either condition is met,

cy.get("table", {timeout: 60000})
  .find("tr[data-index]")          // presumes there's at least one row
  .should("satisfy", ($els) => {
    return $els.length > 1 || $els.text().includes('No results found');
  });

As with any branching code in Cypress, commands will only succeed or fail - you have to dive into jQuery to do conditional stuff.

Upvotes: 1

Alapan Das
Alapan Das

Reputation: 18639

You can use and() to do more than one assertions, something like:

cy.get("table", {
    timeout: 60000
  }).find('tr[data-index]')
  .should('have.length', 0)
  .and('contain', 'No results found')

In case you want to check for one of the two conditions to be true, you can do something like:

cy.get("table", {
    timeout: 60000
}).find('tr[data-index]').then(($ele) => {
    if ($ele.length == 0 || $ele.text() == 'No results found') {
        //Do Something 
    }
    else {
        //Do Something 
    }
})

Upvotes: 1

Related Questions