1

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.

1
  • Is the button submit button on the page but not visible Commented Aug 23, 2019 at 20:35

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

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
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()
I see :) I've updated my answer as well. Updated code should hopefully work.
That works perfectly, thank you! Sorry that I cannot upvote it due to my new/low rep :(
No prob ;) Welcome to SO :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.