javascriptautomationcypresscypress-custom-commands

How to pass locator as parameter in cypress?


I wonder if it is possible to pass locators as a parameter to make my function reusable. I tried to do it myself but I am getting "undefined" instead of working test. Cypress error: cy.click() failed because it requires a DOM element. The subject received was:

undefined

My code:

 Cypress.Commands.add(
  "commandName",
  (locator, chartValue1) => {
    const chartValues = [150, 250, 350, 450, 550, 750, 900];
    for (const value of chartValues) {
      locator.click(value, chartValue1).then(() => {
        mainElementsPage
          .mainSideBarHeader()
          .should("not.include.text", "(pon.)")
          .should("not.include.text", "(wt.)")
          .should("not.include.text", "(śr.)");
      });
    }
  }
);

I am using this command in test:

    it("should do something", () => {
    cy.commandName(mainElementsPage.chartRect(), 200);
  });

mainElementsPage content:

class mainElementsPage {

  chartRect() {
    return cy.get("#chart-grid-rect");
  }
}

export default mainElementsPage;

Solution

  • I went this way:

     Cypress.Commands.add(
      "commandName",
      (locator, chartValue1) => {
        const chartValues = [150, 250, 350, 450, 550, 750, 900];
        for (const value of chartValues) {
          locator()
          .click(value, chartValue1).then(() => {
            mainElementsPage
              .mainSideBarHeader()
              .should("not.include.text", "(pon.)")
              .should("not.include.text", "(wt.)")
              .should("not.include.text", "(śr.)");
          });
        }
      }
    );
    

    And in test it looks:

    it("should do something", () => {
        cy.commandName(mainElementsPage.chartRect, 200);
      });
    

    So the thing was about add () to the locator in Cypress.Commands.add() and use locator as string in the test.