logo
eng-flag

Cypress Cheatsheet

Table of Contents

  1. Installation and Setup
  2. Basic Commands
  3. Selectors
  4. Assertions
  5. Handling Asynchronous Operations
  6. Fixtures and Custom Commands
  7. Debugging
  8. Best Practices

Installation and Setup

Installing Cypress

To install Cypress, run the following command in your project directory:

npm install cypress --save-dev

Opening Cypress

To open the Cypress Test Runner:

npx cypress open

Creating a new spec file

Create a new file in the cypress/integration folder with a .spec.js extension:

touch cypress/integration/my_first_test.spec.js

Basic Commands

Visit a webpage

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

Click an element

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

Type into an input field

cy.get('input[name="username"]').type('testuser')

Clear an input field

cy.get('input[name="username"]').clear()

Submit a form

cy.get('form').submit()

Selectors

By ID

cy.get('#myElementId')

By Class

cy.get('.myClassName')

By Tag Name

cy.get('button')

By Attribute

cy.get('[data-test="submit-button"]')

Chaining Selectors

cy.get('form').find('input[type="email"]')

Assertions

Should Assertion

cy.get('h1').should('have.text', 'Welcome')
cy.get('.error').should('not.be.visible')
cy.get('input').should('have.value', 'Hello')

Multiple Assertions

cy.get('button')
  .should('be.visible')
  .and('have.text', 'Submit')
  .and('not.be.disabled')

Expect Assertion

cy.get('body').then(($body) => {
  expect($body).to.contain('Hello, World!')
})

Handling Asynchronous Operations

Waiting for an Element

cy.get('button', { timeout: 10000 }).should('be.visible')

Waiting for a Network Request

cy.intercept('GET', '/api/users').as('getUsers')
cy.wait('@getUsers')

Retrying Assertions

cy.get('button').should('be.enabled')

Fixtures and Custom Commands

Using Fixtures

cy.fixture('users.json').then((users) => {
  cy.get('input[name="username"]').type(users[0].username)
})

Creating a Custom Command

In cypress/support/commands.js:

Cypress.Commands.add('login', (email, password) => {
  cy.visit('/login')
  cy.get('#email').type(email)
  cy.get('#password').type(password)
  cy.get('form').submit()
})

Using the custom command:

cy.login('user@example.com', 'password123')

Debugging

Pause Execution

cy.pause()

Debug Logging

cy.log('This is a debug message')

Using Browser Dev Tools

cy.get('button').then(($el) => {
  debugger
  // Browser will pause here, allowing you to inspect $el
})

Best Practices

  1. Use data-* attributes for test selectors

    <button data-test="submit-button">Submit</button>
    
    cy.get('[data-test="submit-button"]')
    
  2. Avoid using cy.wait() with arbitrary time values Instead of:

    cy.wait(5000)
    

    Use:

    cy.get('element-to-wait-for', { timeout: 5000 }).should('be.visible')
    
  3. Use cy.intercept() to stub network requests

    cy.intercept('GET', '/api/users', { fixture: 'users.json' })
    
  4. Group related tests using describe() and context()

    describe('User Authentication', () => {
      context('Valid Credentials', () => {
        it('should log in successfully', () => {
          // Test code here
        })
      })
    
      context('Invalid Credentials', () => {
        it('should show an error message', () => {
          // Test code here
        })
      })
    })
    
  5. Use before() and beforeEach() hooks for setup

    beforeEach(() => {
      cy.visit('/')
      cy.login('testuser', 'password123')
    })
    
  6. Avoid sharing state between tests Instead of using global variables, use closures or Cypress aliases:

    it('creates a user and verifies it', () => {
      let userId
      cy.request('POST', '/api/users', { name: 'John Doe' })
        .then((response) => {
          userId = response.body.id
          cy.wrap(userId).as('userId')
        })
    
      cy.get('@userId').then((userId) => {
        cy.visit(`/users/${userId}`)
        cy.get('h1').should('contain', 'John Doe')
      })
    })
    
  7. Use cy.intercept() to test loading states

    cy.intercept('GET', '/api/slow-endpoint', (req) => {
      req.on('response', (res) => {
        res.setDelay(2000)
      })
    }).as('slowRequest')
    
    cy.visit('/page-with-slow-request')
    cy.get('#loading-indicator').should('be.visible')
    cy.wait('@slowRequest')
    cy.get('#loading-indicator').should('not.exist')
    
  8. Use environment variables for sensitive data In cypress.json:

    {
      "env": {
        "api_key": "CYPRESS_API_KEY"
      }
    }
    

    In your test:

    cy.request({
      url: '/api/protected-endpoint',
      headers: {
        'Authorization': `Bearer ${Cypress.env('api_key')}`
      }
    })
    

Remember to never commit sensitive data to version control. Use environment variables or CI/CD secrets management instead.

2024 © All rights reserved - buraxta.com