Cypress.io

How To Use Page Object Model In Cypress

What is Page Object Model (POM)?

Cypress Page Object Model or POM is a design pattern in the automation world that has been famous for its test maintenance approach and avoiding code duplication.

A page object is a class that represents a page in the web application. Under this model, the overall web application breaks down into logical pages.
Each page of the web application generally corresponds to one class in the page object, but can even map to multiple classes also, depending on the classification of the pages.

This Page class will contain all the locators of the WebElements of that web page and will also contain methods that can perform operations on those WebElements.
you can read also on Page object model in another article – 8 Tips To Write Automation Tests Like A Ninja

Our Code

I created a simple test that opens our demo site, by the way it is a great site to practice on.
Searching for the “Element” card and click on it.
Click on the first menu tab and type “This is a test” in the full name field and press submit.

describe('demo', () => {
   it('Test1', ()=> {
     cy.visit('https://demoqa.com')
     cy.get('.card-body').contains('Elements').click()
     cy.get('[class="element-list collapse show"]')
     cy.get('#item-0').click()
     cy.get('#userName').type('This is a test')
     cy.get('#submit').click()
   })
})

Creating The POM Class

To create the Page Object Model class we will create a new folder under the support section and inside adding our file.js – for the demo, I created a test.js file.

This is the template for every POM class:
The function VisitSite() include the cy.visit command

export class Demo{

   VisitSite(){
       cy.visit('https://demoqa.com')
   }
}
export const utilities = new Demo()

Importing The Class To Our Test

Going back to our test file we now need to import the POM class so we will be able to use the VisitSite() function we created.

import {utilities} from "../../support/page_object/test"

After we imported the class we can now use the function inside the test.

utilities.VisitSite()

The final result will look like that:

describe('demo', () => {
    it('Test1', ()=> {

      utilities.VisitSite()

      cy.get('.card-body').contains('Elements').click()
      cy.get('[class="element-list collapse show"]')
      cy.get('#item-0').click()
      cy.get('#userName').type('This is a test')
      cy.get('#submit').click()
    })
 })

Ofir Blumental

QA Automation Engineer - ofirblumental1@gmail.com

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button