skip to Main Content

I have some code below to check if a checkbox is checked or not. Even if the checkbox is checked, it says that its not. Why does the code fail and how to fix it?

function isChecked(locator : string) : boolean {
 let checked : boolean = false;
 cy.get(locator).then(el){
  if(el.val() === "on"){
   checked = true;//Is actually true when element is checked.
  }
 }
 return checked;//Is actually false when element is checked.
}

2

Answers


  1. Rewrite your function in this way and check if it works:

    function isChecked(locator) {
      let checked = false;
      
      cy.get(locator).then((el) => {
        if (el.prop('checked')) {
          checked = true;
        }
      });
      
      return checked;
    }
    
    Login or Signup to reply.
  2. function isChecked(locator) {
      return new Cypress.Promise((resolve) => {
        cy.get(locator).then((el) => {
          resolve(el.prop('checked'));
        });
      });
    }
    
    isChecked('#myCheckbox').then((checked) => {
      if (checked) {
        // Checkbox is checked
      } else {
        // Checkbox is not checked
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search