Custom Commands for Reusable Test Actions
Intermediatev1.0.0
Build Cypress custom commands to encapsulate repetitive test actions — authentication flows, API interactions, form filling, and assertion helpers used across your test suite.
Content
Overview
Cypress custom commands extend the cy object with reusable actions. Instead of duplicating login flows, API calls, and complex interactions in every test, encapsulate them in commands that read naturally and maintain easily.
Why This Matters
- -DRY tests — login flow written once, used in hundreds of tests
- -Readability —
cy.login(user)reads better than 5 lines of form filling - -Maintainability — when the login flow changes, update one command
How It Works
Step 1: Define Custom Commands
Step 2: Create Authentication Command with Session Caching
Step 3: Use in Tests
Best Practices
- -Use
cy.session()for login commands — caches auth state across tests - -Use
cy.request()for API-based setup (faster than UI interactions) - -Always add TypeScript declarations for IDE autocompletion
- -Name commands with verbs:
login,seedDatabase,clearNotifications - -Keep commands focused — one action per command
Common Mistakes
- -Creating commands for actions used in only one test (over-abstraction)
- -Commands that contain assertions (commands should act, tests should assert)
- -Not using
cy.session()for auth (re-logs in for every test — slow) - -Forgetting TypeScript declarations (no autocompletion)
FAQ
Discussion
Loading comments...