Verify login form elements using best practice selectors
Preconditions (1)
✅ Expected Result: The login form fields are located using best practice selectors, login is successful, and user is redirected to the dashboard page
describe('Login form test with best practice selectors', () => { beforeEach(() => { cy.visit('/login'); }); it('should login successfully using data-cy selectors', () => { cy.get('[data-cy=email-input]') .should('be.visible') .type('user@example.com'); cy.get('[data-cy=password-input]') .should('be.visible') .type('Password123!'); cy.get('[data-cy=login-button]') .should('be.visible') .click(); cy.url().should('include', '/dashboard'); }); });
This test uses data-cy attributes as selectors, which are stable and not affected by styling or layout changes.
Each element is first checked to be visible before interacting, ensuring the test waits for the element properly.
The test types into the email and password fields, then clicks the login button.
Finally, it asserts that the URL includes '/dashboard' to confirm successful login.
This approach avoids brittle selectors like classes or XPath and uses Cypress commands consistently for clarity and maintainability.
Now add data-driven testing with 3 different sets of valid login credentials
data-test='submit-btn' in Cypress?<button data-cy='login-btn' class='btn primary'>Login</button>What will
cy.get('.btn.primary').click() do if the class changes to btn secondary later?cy.get('button.submit-btn') but the test fails because the button has no class submit-btn. How can you fix it following best practices?data-test='save-btn'. The form has multiple buttons with different data-test attributes. Which selector is best to ensure you click the correct button inside the form?Pass the test and this pattern moves unknown