3
///\<reference types = "cypress"/\>
///\<reference types = "cypress-xpath"/\>
describe("Interacting with dropdowns", function () {
  it("Auto Suggest Dynamic Dropdown: We need to write function", function () {
    cy.visit("https://www.google.com/");
    cy.wait(2000);
    cy.get(".gLFyf").type("Automation Testing");
    cy.wait(5000);
    cy.get(".wM6W7d>span").should("have.length", "12");
    cy.get(".wM6W7d>span").each(($el, index, $list), function () {
      if ($el.text() == "automation testing tutorial") {
        cy.wrap($el).click();
      }
    });
    cy.get(".gLFyf").should("have.value", "Automation Testing");
  });
});

While execution I am getting referenceerror.Unable to execute the code in cypress and also getting the "ReferenceError" i.e., $el is not defined .

Phil
  • 157,677
  • 23
  • 242
  • 245
  • 1
    Your syntax is off for `.each()`. Simply replace `, function ()` with `=>`. See https://docs.cypress.io/api/commands/each – Phil Aug 10 '23 at 06:59

1 Answers1

1

You can try out this code and update it according to your need.

describe("Interacting with dropdowns", function () {
  it("Auto Suggest Dynamic Dropdown: We need to write function", function () {
    cy.visit("https://www.google.com/");
    cy.wait(2000);
    cy.get(".gLFyf").type("Automation Testing");
    cy.wait(5000);
    cy.get(".wM6W7d>span").should("have.length", "12");
    cy.get(".wM6W7d>span").then((result) => {
      for (const item of result) {
        if (item.innerText == "automation testing tutorial") {
          cy.get(`.${item.offsetParent.className}`).click();
        }
      }
      cy.wait(2000);
      cy.contains(`Automation Testing`);
    });
  });
});

Here is the snap of the result:

enter image description here

Here with the help of the method, we retrieved the result and executed the click event based on the matching condition.

I believe each is not able to properly find the iterable. For more detail regarding each, please go through the documentation link :

https://docs.cypress.io/api/commands/each

Hope this helps! Happy coding :)

Harsh nahta
  • 176
  • 1
  • 14