0

I'm trying to use a pageObject in Cypress, I want to have my selectors in the same file so I can reuse them in multiple functions and only need to change them in one place if they need updating.

Here is a simple example:

class HomePage {
  searchLink = "a[class='search button']";

  clickSearchLink() {
    cy.get(this.searchLink).click();
  }
}

export const homePage = new HomePage();

This works fine, my test can call the functions e.g. homePage.clickSearchLink() but I have two issues:

  1. When I run eslint it fails with

e2e/page-objects/home-page.js 2:14 error Parsing error: Unexpected token =

  1. Doing it this way means searchLink is available in my spec files, I want it to only be seen in this class. I tried setting searchLink to a let or var but that just made it unusable in the clickSearchLink() function.

Is it possible to have my selectors in this class and still pass linting?

Fody
  • 23,754
  • 3
  • 20
  • 37
Doctor Who
  • 1,287
  • 5
  • 25
  • 46

1 Answers1

1

If you bump the Typescript target to es6/es2015 you can use private fields.

Private Class Features

Private class features

Class fields are public by default, but private class members can be created by using a hash # prefix. The privacy encapsulation of these class features is enforced by JavaScript itself.

For the ESLint error, add a constructor.

class HomePage {
  #searchLink: string;
  
  constructor() {
    this.#searchLink = "a[class='search button']";
  }

  clickSearchLink() {
    cy.get(this.#searchLink).click();
  }
}

export const homePage = new HomePage();

/cypress/tsconfig.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "target": "es6",
    ...
  },
  "include": ["**/*.ts"]
}
Fody
  • 23,754
  • 3
  • 20
  • 37