0
0
Cypresstesting~5 mins

App Actions pattern in Cypress

Choose your learning style9 modes available
Introduction

The App Actions pattern helps organize test steps into clear, reusable actions. It makes tests easier to read and maintain.

When you want to reuse common steps like logging in or filling forms in many tests.
When your test code is getting long and hard to understand.
When you want to separate what the test does from how it does it.
When you want to make your tests easier to update if the app changes.
Syntax
Cypress
class AppActions {
  login(username, password) {
    cy.get('#username').type(username)
    cy.get('#password').type(password)
    cy.get('button[type="submit"]').click()
  }

  addItemToCart(itemName) {
    cy.contains(itemName).click()
    cy.get('#add-to-cart').click()
  }
}

// Usage in test
const app = new AppActions()
app.login('user1', 'pass123')
app.addItemToCart('Book')

Define actions as methods inside a class or object.

Use Cypress commands inside these methods to perform UI steps.

Examples
A simple action to log out from the app.
Cypress
class AppActions {
  logout() {
    cy.get('#logout').click()
  }
}
An action to perform a search with a given term.
Cypress
class AppActions {
  search(term) {
    cy.get('#search-box').type(term)
    cy.get('#search-button').click()
  }
}
Sample Program

This test uses the App Actions pattern to login and add an item to the cart. It checks the URL after login and verifies the cart contains the item.

Cypress
class AppActions {
  login(username, password) {
    cy.get('#username').type(username)
    cy.get('#password').type(password)
    cy.get('button[type="submit"]').click()
  }

  addItemToCart(itemName) {
    cy.contains(itemName).click()
    cy.get('#add-to-cart').click()
  }
}

describe('Shopping Cart Tests', () => {
  const app = new AppActions()

  it('should login and add a book to the cart', () => {
    cy.visit('/login')
    app.login('user1', 'pass123')
    cy.url().should('include', '/dashboard')

    app.addItemToCart('Book')
    cy.get('#cart-items').should('contain', 'Book')
  })
})
OutputSuccess
Important Notes

Keep actions focused on one task each for clarity.

Use meaningful method names to describe the action.

Update actions if UI selectors or flows change to keep tests working.

Summary

App Actions pattern groups test steps into reusable methods.

This makes tests cleaner and easier to maintain.

Use it to simplify common tasks like login or adding items.