Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress - if then functions

I have question about Cypress.

I have an element on page which doesn't appear allways. There is no logic when it shows and when not.

Is in Cypress some IF/THEN function or something how do you check if the element is displayed (so fill it up) and when you don't see it than skip that step?

My code:

if (Cypress.$('[data-bind="validationElement: interestInsurable"]').length > 0) {
            cy.get('[for="p4-conditional-csob-interest-insurable-1"]').click()        
        }
else {cy.get('#car-info-serie')}

This is how it looks like in playground: Picture

And there is HTML of that checkbox:

<label class="z-radio z-radio-inline primary" for="p4-conditional-csob-interest-insurable-1" data-bind="popover: { content: VehicleInsuranceTooltips.conditionalDataCsobInterestInsurable1Tooltip }" data-original-title="" title="">
    <input id="p4-conditional-csob-interest-insurable-1" name="p4-conditional-csob-interest-insurable" type="radio" class="custom-radio" data-toggle="radio" data-bind="checkedValue: 1, checked: interestInsurable" value="1">
<span class="icons">
<span class="icon-unchecked"></span>
<span class="icon-checked"></span>
</span>
Patří vozidlo zájemci o pojištění?
</label>
like image 358
Dominik Skála Avatar asked Nov 23 '18 13:11

Dominik Skála


People also ask

How do you write a conditional statement in Cypress?

Conditionally check whether an element has certain text: get('body'). then(($body) => { // synchronously ask for the body's text // and do something based on whether it includes // another string if ($body. text(). includes('some string')) { // yup found it cy.

What is the use of then in Cypress?

then() allows you to use the yielded subject in a callback function and should be used when you need to manipulate some values or do some actions. When using a callback function with . should() or . and() , on the other hand, there is special logic to rerun the callback function until no assertions throw within it.


1 Answers

There is no built in way to do this in cypress. I am using this in my tests:

if (Cypress.$("#yourElement").length > 0) {
  // element exists, do something
} else {
  // element does not exist, do something else
}
like image 163
Brendan Avatar answered Oct 18 '22 20:10

Brendan