Installation
- npm install cypressInstall
- npx cypress openOpen GUI
- npx cypress runRun headless
- npx cypress verifyVerify install
Selectors
- cy.get('selector')CSS selector
- cy.contains('text')By text
- cy.get('[data-cy=id]')By data attr
- .find('child')Find child
- .first() / .last()First/last
- .eq(index)By index
Actions
- .click()Click element
- .type('text')Type text
- .clear()Clear input
- .check() / .uncheck()Checkbox
- .select('option')Select dropdown
- .trigger('event')Trigger event
- .scrollIntoView()Scroll to
Assertions
- .should('exist')Element exists
- .should('be.visible')Is visible
- .should('have.text', 'x')Has text
- .should('have.value', 'x')Input value
- .should('have.class', 'x')Has class
- .should('be.disabled')Is disabled
- .should('have.length', n)Count
Basic Test Structure
describe('Login Page', () => {
beforeEach(() => {
cy.visit('/login');
});
it('should login with valid credentials', () => {
cy.get('[data-cy=email]').type('user@example.com');
cy.get('[data-cy=password]').type('password123');
cy.get('[data-cy=submit]').click();
cy.url().should('include', '/dashboard');
cy.contains('Welcome').should('be.visible');
});
});
Custom Commands (cypress/support/commands.js)
// Define custom command
Cypress.Commands.add('login', (email, password) => {
cy.visit('/login');
cy.get('[data-cy=email]').type(email);
cy.get('[data-cy=password]').type(password);
cy.get('[data-cy=submit]').click();
});
// Use in test
cy.login('user@example.com', 'password123');
CLI Options
- --browser chromeBrowser
- --spec "path/**"Run specific
- --headedShow browser
- --env key=valSet env var
- --recordRecord to Cloud
Network Requests
- cy.intercept()Intercept request
- cy.wait('@alias')Wait for request
- cy.request()HTTP request
- .as('alias')Create alias
API Mocking
// Intercept and mock API response
cy.intercept('GET', '/api/users', {
statusCode: 200,
body: [{ id: 1, name: 'John' }]
}).as('getUsers');
cy.visit('/users');
cy.wait('@getUsers');
// Intercept and modify
cy.intercept('POST', '/api/login', (req) => {
req.reply({ token: 'fake-token' });
});
Fixtures
// Load fixture file
cy.fixture('users.json').then((data) => {
// use data
});
// Use in intercept
cy.intercept('GET', '/api/users', {
fixture: 'users.json'
});
Viewport & Screenshots
- cy.viewport(w, h)Set viewport
- cy.viewport('iphone-x')Preset device
- cy.screenshot()Take screenshot
- .screenshot('name')Named screenshot