Cypress Cheat Sheet

Cypress is a JavaScript end-to-end testing framework. Here’s a cheat sheet covering some common commands and concepts in Cypress:

Installation

Install Cypress:

npm install cypress --save-dev

Open Cypress GUI:

npx cypress open

Writing Tests

Create a Test File:

  • Cypress tests are typically written in files with the extension .spec.js.
// cypress/integration/example.spec.js
describe('My Test Suite', function () {
  it('My Test Case', function () {
    // Test code goes here
  });
});

Visit a URL:

cy.visit('https://example.com');

Assertions:

cy.get('.element').should('have.text', 'Expected Text');

Interacting with Elements

Click an Element:

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

Type into an Input:

cy.get('input[type="text"]').type('Text to type');

Select from Dropdown:

cy.get('select').select('Option Value');

Asynchronous Actions

Working with Promises:

cy.get('.element').then(($element) => {
  // Work with the element using jQuery
});

Hooks

Before Each Hook:

beforeEach(() => {
  // Code to run before each test
});

After Each Hook:

afterEach(() => {
  // Code to run after each test
});

Before All Hook:

before(() => {
  // Code to run once before all tests
});

After All Hook:

after(() => {
  // Code to run once after all tests
});

Custom Commands

Create a Custom Command:

  • Add the following in commands.js:
Cypress.Commands.add('customCommand', () => {
  // Custom command logic
});
  • Use it in a test:
cy.customCommand();

Configuration

  • Configuration File:
    • Create a cypress.json file in your project.
  • Configuration Options:
    • Adjust settings like baseUrl, viewport size, etc.
{
  "baseUrl": "https://example.com",
  "viewportWidth": 1280,
  "viewportHeight": 720
}

This cheat sheet provides a quick reference for common Cypress commands and concepts. Refer to the official documentation for detailed information and advanced usage.