Search

Page Objects in Cypress

Page objects are used to get the access of web page's elements from a common place. It is mainly used for Code re-usability and Maintainability.



To create Page objects in Cypress, create a folder 'PageObjects' under Integration folder and create '.js' file based on which page you are going to create your page objects.


Create and class and methods to add page objects for each field in the page and add an export statement.


To access them in your tests,


1. Import the class from the defined path

import ContactPageObjects from "../PageObjects/ContactPageObjects.js"

2. Create object for that class

const contact = new ContactPageObjects()

3. access them in code using the object created.

contact.name()
contact.email().type('data')


Complete Code:


ContactPageObjects.js


class ContactPageObjects{
 name(){
 return cy.get('#input_comp-kntvy6i7')
    }
 email(){
 return cy.get('#input_comp-kntvy6ir')
    }
 subject(){
 return cy.get('#input_comp-kntvy6j4')
    }
 message(){
 return cy.get('#textarea_comp-kntvy6jb')
    }
}

export default ContactPageObjects

ContactTest.js


import ContactPageObjects from "../PageObjects/ContactPageObjects.js"
describe('testing custom commands',()=>{
 const contact = new ContactPageObjects()
 it('custcommands test1',()=>{
 cy.visit('https://coderscamp.wixsite.com/codeit')
 cy.contains('Contact').click()
 contact.name().type('coderscamp')
 contact.email().type('coderscampindia@gmail.com')
 contact.subject().type('testing custom commands')
 contact.message().type('All the best',{sensitive:true})
 cy.get('[data-testid=buttonElement]').click()
    })
})

You have learned today how to add page objects in cypress!! Happy Testing!!

52 views0 comments

Recent Posts

See All

A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The f

The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on.