0

I am writing a Cypress test on a quiz page with a random # of pages. I am trying to write a condition in Cypress that will allow me to click on a "SUBMIT" page link if it is the last page, else it will click on a "NEXT" link if it is not the last page.

I have tried using cypress commands such as .contains() and .find() which does not seem to return a pass/fail response. I have also tried various if statements, but when I use these, I end up using cypress commands that either pass or fail, but do not route to any alternate conditional else.

//Clicks on submit successfully or fails the test. Never hits the else clause if not the last page.

        if (cy.find("button[data-cy=submitBtn]").length > 0) 
        {
            // SUBMIT button exists
            cy.get('[data-cy=submitBtn]')
                .click()
        }

Expected result will hit the else if the condition is met and trigger the command.

slamey
  • 11
  • 2
  • 5

1 Answers1

4

This should be the condition you're looking for:

cy.get("body").then($body => {
  if ($body.find("button[data-cy=submitBtn]").length > 0) {   //evaluates as true
     cy.get("button[data-cy=submitBtn]")
     .click();
  }
});

I believe your question might be a duplicate of this one

DurkoMatko
  • 5,238
  • 4
  • 26
  • 35
  • I got this error when trying this: CypressError: Oops, it looks like you are trying to call a child command before running a parent command. You wrote code that looks like this: cy.find("button[data-cy=submitBtn]") A child command must be chained after a parent because it operates on a previous subject. For example - if we were issuing the child command 'click'... cy .get('button') // parent command must come first .click() // then child command comes second – slamey Aug 23 '19 at 19:27
  • Can you update your code in the question with the current code? If you want to click on that button you have to get it first with .get()...Code I posted is just a condition to determine whether that button exists at all. If it does and condition is true, then you have to do `cy.get('[data-cy=submitBtn]').click()` – DurkoMatko Aug 23 '19 at 19:33
  • I see :) I've updated my answer as well. Updated code should hopefully work. – DurkoMatko Aug 23 '19 at 19:47
  • 3
    That works perfectly, thank you! Sorry that I cannot upvote it due to my new/low rep :( – slamey Aug 23 '19 at 19:50
  • No prob ;) Welcome to SO :) – DurkoMatko Aug 23 '19 at 19:56