Cypress
Course Index
Index

Cypress Advanced

Handling Asynchronous Actions


Auto-waiting Example

Javascript
Copy
cy.get('#loading').should('not.exist'); // Waits until the element disappears

Wait for API Response

Javascript
Copy
cy.intercept('GET', '/api/data').as('getData');
cy.wait('@getData').its('response.statusCode').should('eq', 200);

Custom Commands


Define a Custom Command (cypress/support/commands.js)

Javascript
Copy
Cypress.Commands.add('login', (email, password) => {
  cy.visit('/login');
  cy.get('#email').type(email);
  cy.get('#password').type(password);
  cy.get('button').click();
});

Use Custom Command in Tests

Javascript
Copy
cy.login('user@example.com', 'password');

Network Requests (API Testing)


GET Request

Javascript
Copy
cy.request('GET', '/api/users').then((response) => {
  expect(response.status).to.eq(200);
});

POST Request

Javascript
Copy
cy.request('POST', '/api/login', {
  username: 'admin',
  password: '12345'
}).its('status').should('eq', 200);

Mock API Response (cy.intercept)

Javascript
Copy
cy.intercept('GET', '/api/user', { fixture: 'user.json' }).as('getUser');
cy.visit('/profile');
cy.wait('@getUser');

Debugging & Reporting


Pause Execution

cy.pause(); // Pauses test for inspection

Debug with Cypress Console

cy.get('button').click().debug();

Take Screenshot

cy.screenshot('login-page');

Record Video (via cypress.config.js)

module.exports = { video: true };

Continuous Integration (CI/CD)


Run Cypress in CI

1. Add the following code to your CI config (e.g., GitHub Actions)

- name: Run Cypress Tests run: npx cypress run

2. Parallel Execution with Dashboard Key

npx cypress run --record --parallel --key

Handling Environment Variables


Define in cypress.env.json

{ "apiKey": "your-api-key" }

Access in Tests

const apiKey = Cypress.env('apiKey');

Pass via CLI

npx cypress run --env apiKey=12345