We use cy.get() to find elements on a web page so we can test them. CSS selectors help us pick exactly the right elements.
0
0
cy.get() with CSS selectors in Cypress
Introduction
When you want to click a button on a page during a test.
When you need to check if a specific text box is visible.
When you want to verify that a list contains certain items.
When you want to fill out a form field by selecting it.
When you want to check the style or class of an element.
Syntax
Cypress
cy.get('css-selector')
The css-selector is a string that tells Cypress which element(s) to find.
You can use any valid CSS selector like class, id, attribute, or element type.
Examples
Selects the element with the id
submit-button.Cypress
cy.get('#submit-button')
Selects all elements with the class
nav-item.Cypress
cy.get('.nav-item')
Selects the input element with the attribute
name equal to email.Cypress
cy.get('input[name="email"]')
Selects all
button elements with the class primary.Cypress
cy.get('button.primary')
Sample Program
This test visits a login page, finds the email and password fields by their CSS selectors, types in values, clicks the submit button, and checks if a welcome message appears.
Cypress
describe('Login form test', () => { it('should find and type email', () => { cy.visit('https://example.com/login') cy.get('input#email').type('user@example.com') cy.get('input#password').type('password123') cy.get('button[type="submit"]').click() cy.get('.welcome-message').should('be.visible') }) })
OutputSuccess
Important Notes
Always use unique and stable CSS selectors to avoid flaky tests.
Use IDs when possible because they are fast and unique.
You can chain cy.get() with other commands like .click(), .type(), and .should().
Summary
cy.get() finds elements using CSS selectors.
Use simple and clear CSS selectors for reliable tests.
Combine cy.get() with actions and assertions to test web pages.