Cypress Locators

Profile picture for user devraj

Well if you have worked on Selenium or any other Web Automation tool, you already know what locators is. Locators are basically identifiers that tells any automation tool which element it needs to operate for testing. 

Cypress also use locators to identify the UI elements like text box, button, radio button or checkbox. Now, question is what locators are supported by Cypress. Cypress supports jQuery selectors which is basically derived from css selectors. Surprising thing is that Cypress does not support XPath however you can use an external plugin Cypress-Xpath. 

Locators in Cypress

Here are some locating techniques:

1. Tag Name: Give any tag name like input, button or div etc. Example.

cy.get('textarea');

2. ID: Use # symbol with id value.

cy.get('#inputEmail1');

3. Class Name and Value: Use dot(.) with single class value. Multiple classes are separated with spaces.

// Use . with single class name
cy.get('.status-danger');

// Use multiple classes
cy.get('[class="appearance-filled size-medium shape-rectangle status-danger nb-transition"]')

4. Attribute Name, Value and Multiple Attributes

// By Attribute Name
cy.get('[placeholder]');

// By Attribute Name and Value
cy.get('[placeholder="Email"]')

///By Multiple Attributes
cy.get('[placeholder="Email"][type="Email"]')

5. Combination of Tags and Attributes

// Using tag name with class
cy.get('input.status-danger');

// using tag name with id
cy.get('input#inputEmail1');

// using tag name with any other attribute
cy.get('input[placeholder="Email"]')

// using tag name with class, ID and attribute
cy.get('[placeholder="Email"].input-full-width#inputEmail1')