top of page
Cypress Tutorial
Locators In Cypress
What Are Cypress Locators ?
Cypress locators or selectors are an object in a form of expressions that identify the HTML/web elements uniquely of the web page. In automation, to perform different operations on the web elements first, we need to identify a web element then perform actions on that element.
Cypress only supports CSS selector and jquery selector. However, for xpath selector, we need to install a third-party plugin which is cypress-xpath .
To fetch the HTML element by locating them in Cypress cy.get() method is used. E.g. cy.get('locator')
The syntax of the CSS selector can be written in following ways :
Using Id
Using Class
Using Attribute
Using Tag
Create CSS selector using Id in Cypress
Id is an attribute of HTML tag that can be used to loacte a web element.
The value of the id attribute is directly passed with the prefix '#'(hash) to the cypress command cy.get() .
Syntax :
cy.get('#idValue')
Consider the following code as an example :
To locate the element by id in cypress, use cy.get() method :
cy.get('#user_signup_email')
Example :
To Run :
Open cypress : npx cypress open
Run command : npx cypress run --spec 'cypress/e2e/ById.cy.js'
Create CSS selector using Class in Cypress
Class is also an attribute of an HTML element and can be used as a locator.
Prefix '.'(dot) is used with the value class attribute and then pass it to the method cy.get() .
Syntax :
cy.get('.classValue') OR
cy.get('tagName[class="classValue"]')
Consider the following code :
To locate it by class, use cy.get() :
cy.get('.user_signup_wrapper') OR
cy.get('input[class="user_signup_wrapper"]')
Example :
To Run :
Open cypress : npx cypress open
Run command : npx cypress run --spec 'cypress/e2e/ByClass.cy.js'
Create CSS selector using Attribute in Cypress
In the DOM most of the tags have some attributes, we can use their attributes as a locator.
Syntax :
cy.get('tagName[attributeName="attibuteValue"]')
Consider the following code :
To locate it by attribute, use cy.get() :
cy.get('input[type="mail"]')
Example :
To Run :
Open cypress : npx cypress open
Run command : npx cypress run --spec 'cypress/e2e/ByTagAttribute.cy.js'
Create CSS selector using Tag in Cypress
Web pages are developed using tags and these tags can be used to locate web elements.
Syntax :
cy.get('tagName')
Consider the following code :
Locating it by tag using cy.get() :
cy.get('input')
Some commands that can be applied on Locators
click() : To click on a hyperlink, e.g. cy.get('locator').click()
type() : To type in any text field, e.g. cy.get('locator').type("Write Something Here")
Refer next page Get And Find Command
bottom of page