Protecting test selectors from outside Page Objects

Viewed 26

I'm building page objects for the team to use in Cypress tests. The idea is to encapsulate the selectors so that when they change I update in one place and everyone's tests remain functional.

The problem is the class fields are accessible /modifiable from the tests. How do I prevent access to the selectors directly?

Example PO:

class ProductPage {
  
  product: string = 'select#product'
  productOptions: string = 'select#product option'

  selectProduct(productName) {
    cy.get(this.product).select(productName);
  }
}

export const products = new ProductPage();
1 Answers

You need to use hash names (fields starting #) to protect the class inner fields.

You should also separate declaration and initialization of the fields.

class ProductPage {
  
  #product: string 
  #productOptions: string

  constructor() {
    this.#product = 'select#product'
    this.#productOptions = 'select#product option'
  }

  selectProduct(productName) {
    cy.get(this.#product).select(productName);
  }
}

export const products = new ProductPage();
Related