0

I'm doing a test and I put a value in a texfield. If I get some data I want it to be found, otherwise I want "no data" to be found. This code doesn't work... Why? And how can I do it?

it('Test on filter', function () {
  const valueInserted = 'VALUE';
  cy.get('#autorouter-patname').type(valueInserted);
  cy.get('button[type="submit"]'.click();
  cy.get('tbody>tr>td')
   .then(($el) => {
    if (cy.get($el).contains('No data available')) {
      return cy.contains('No data available')
    } else {
      return cy.get($el).eq(2).contains(valueInserted);
    }
 })
})
3
  • When you say doesn't work, presumably it always goes down the truth-y path?
    – jonrsharpe
    Commented Mar 25, 2021 at 14:03
  • yes, it only checks the first condition and, if this is not true, the test fails and does not enter the else
    – dx584905
    Commented Mar 25, 2021 at 14:08
  • Because .contains doesn't return a boolean, if no element is found an error is thrown. Try getting the text as shown in e.g. docs.cypress.io/faq/questions/….
    – jonrsharpe
    Commented Mar 25, 2021 at 14:10

1 Answer 1

2

You are trying to use the contains command from cypress to get a boolean, but it acts like an assertion itself. It tries to search something that contains the provided text and if gets no results, the test fails. I am doing conditional testing like this:

cy.get('body').then(($body) => {
    if ($body.find('._md-nav-button:contains("' + name + '")').length > 0) {
      cy.contains('._md-nav-button', name).click();
    }
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.