Concept Explanation
Cypress is a tool that literally opens a browser and clicks buttons for you. It types in forms, navigates pages, and checks if the text on screen is correct.
It is the final layer of safety. It ensures that after all your coding, a real user can still complete their goals (like "Buying a Product").
Syntax or Core Structure
A Cypress Test
describe('Login Flow', () => {
it('should log in a user successfully', () => {
cy.visit('/login');
cy.get('input[name="username"]').type('alice');
cy.get('input[name="password"]').type('password123');
cy.get('button#login-btn').click();
cy.url().should('include', '/dashboard');
cy.get('h1').contains('Welcome back, Alice');
});
});
Best Practices
- Don't rely on IDs: Use specialized data attributes like
data-cy="login-button". This keeps your tests from breaking if you change the CSS ID. - Independent Tests: A test should never rely on a previous test. Each test should start with a "Clean Slate."
- Visual Evidence: Cypress automatically records videos and takes screenshots when a test fails. Always check them!
Practice Exercises
- The Script Writer: Write a mock Cypress script that "Searches for a product" on an e-commerce site.
- The Assertion: Research the
.should()command in Cypress. List 3 different things you can check for (e.g., visibility, text content). - The CI/CD Link: Research why we run Cypress tests in a "Headless" browser during deployment.