Home > Software design >  Conditional test cypress
Conditional test cypress

Time:10-26

I have a button which has two status, one activate and one deactivate. By clicking on it you can de/activate a driver. Im using cypress to test this button and below is part of the test:

cy.get('button').then(($btn) => {
        if ($btn.has('[data-cy="activate-user-account"]')) {
            cy.get('[data-cy="activate-user-account"] span').click();
            cy.get('.btn-primary > .button-wrapper').click();
            cy.get('.btn > .ng-star-inserted svg').click();
        }
        else {
            cy.get('[data-cy="deactivate-user-account"] span').click();
            cy.get('.btn-primary > .button-wrapper').click();
            cy.get('.btn > .ng-star-inserted svg').click();

        }
    });

But what it does, it only looks at the else and tries to execute that one, without considering if part. What Im doing wrong in here?

Im new to cypress, apologies if this is an easy one and I don't know it ;)

enter image description here

CodePudding user response:

JQuery has() function returns not a boolean value but a jquery object itself. So the correct way to check the condition is the following:

$btn.has('[data-cy="activate-user-account"]').length

And this is the complete code snippet:

cy.get('button').then(($btn) => {
        if ($btn.has('[data-cy="activate-user-account"]').length) {
            cy.get('[data-cy="activate-user-account"] span').click();
        } else {
            cy.get('[data-cy="deactivate-user-account"] span').click();
        }
        cy.get('.btn-primary > .button-wrapper').click();
        cy.get('.btn > .ng-star-inserted svg').click();
    });

CodePudding user response:

Eventually below code worked:

Need to address the element via parents and container label. Also length > 0 is important when the element is called and it has a value.

Problem with the code above was that it couldn't find the element at first. that's why it skipped the if condition and executed the else. So make sure the test finds the exact element, then you can expect that if condition will work. Below is the complete right answer.

cy.contains( '{Parent}','{elementLabel}')
        .find('[type="button"]')
        .then(($btn) => {
        if ($btn.find('[data-cy="activate-user-account"]').length > 0 ) {
            cy.get('[data-cy="activate-user-account"] span').click();
        } else {
            cy.get('[data-cy="deactivate-user-account"] span').click();
        }
        cy.get('.btn-primary > .button-wrapper').click();
    });
  • Related