Cypress Basics
Cypress Setup & Configuration
Install Cypress:
npm install cypress --save-dev
Open Cypress Test Runner
npx cypress open
Run Cypress in Headless Mode
npx cypress run
Cypress Folder Structure
cypress/
├── e2e/ # Test files
├── fixtures/ # Mock data
├── support/ # Custom commands & utilities
│ ├── commands.js
│ └── e2e.js
└── cypress.config.js # Cypress configuration
Basic Configuration (cypress.config.js)
Javascript
Copy
const { defineConfig } = require('cypress'); module.exports = defineConfig({ e2e: { baseUrl: 'http://localhost:3000', viewportWidth: 1280, viewportHeight: 720, retries: { runMode: 2, // Retries for CI runs openMode: 0 // No retries locally } } });
Basic Cypress Commands
Visit a Page
Javascript
Copy
cy.visit('/login'); // Relative to baseUrl cy.visit('https://example.com');
Get Elements
Javascript
Copy
cy.get('button'); // By tag cy.get('#username'); // By ID cy.get('.submit-btn'); // By class cy.contains('Submit'); // By text cy.get('[data-test="login"]'); // By attribute
Interact with Elements
Javascript
Copy
cy.get('#username').type('user123'); // Type input cy.get('#password').clear(); // Clear input cy.get('button').click(); // Click button cy.get('select').select('Option 1'); // Select dropdown
Assertions
Javascript
Copy
cy.get('.success').should('be.visible'); // Check visibility cy.get('h1').should('contain', 'Welcome'); // Text match cy.url().should('include', '/dashboard'); // URL check cy.get('input').should('have.value', 'user'); // Input value
Working with Forms
Javascript
Copy
cy.get('#email').type('user@example.com'); cy.get('#password').type('password'); cy.get('form').submit();
Check and Uncheck
Javascript
Copy
cy.get('#agree').check(); cy.get('#agree').uncheck();
File Uploads
1. Install File Upload Package
npm install cypress-file-upload --save-dev
2. Import in Support File
import 'cypress-file-upload';
3. Upload File in Test
cy.get('input[type="file"]').attachFile('file.pdf');
Assertions
Element Assertions
Javascript
Copy
cy.get('.alert').should('have.class', 'success'); cy.get('#logout').should('exist'); cy.get('input').should('be.disabled');
URL Assertions
Javascript
Copy
cy.url().should('include', '/dashboard'); cy.location('pathname').should('eq', '/dashboard');
Network Assertions
Javascript
Copy
cy.intercept('POST', '/api/login').as('login'); cy.wait('@login').its('response.statusCode').should('eq', 200);
Handling Windows, Tabs & Iframes
Handle New Tabs
Cypress cannot switch tabs but can open links in the same window
Javascript
Copy
cy.get('a').invoke('removeAttr', 'target').click();
Handle Iframes
1. Install iframe plugin (optional)
npm install cypress-iframe --save-dev
2. Access iframe
Javascript
Copy
cy.frameLoaded('#iframe'); cy.iframe().find('button').click();
Test Execution
Run Specific Test Files
npx cypress run --spec "cypress/e2e/login.cy.js"
Run Tests in a Specific Browser
npx cypress run --browser chrome
Run Tests in Headed Mode (with UI)
npx cypress run --headed