Skip to content
Advertisement

How can I do an if else in cypress?

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);
    }
 })
})

Advertisement

Answer

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();
    }
});
Advertisement