cypress-reea-template
v1.0.4
Published
A comprehensive Cypress testing template with Page Object Model, custom commands, email testing, and automatic PO generation
Downloads
12
Maintainers
Readme
🚀 Cypress Reea Template
A comprehensive, production-ready Cypress testing template with advanced features including Page Object Model, custom commands, email testing capabilities, and automatic Page Object generation.
✨ Features
- 🎯 Page Object Model (POM) - Structured, maintainable test architecture
- 🔧 Custom Commands - Extended Cypress functionality with visit aliases and session-based login
- 📧 Email Testing - IMAP integration for email verification workflows
- 🤖 Auto PO Generator - CLI tool to generate Page Objects automatically
- 📊 Reporting - Mochawesome integration for beautiful HTML reports
- 🔐 Multi-Environment - Dev, Stage, and Prod environment support
- 🛠️ Helper Functions - 20+ utility functions for common test operations
- 📝 TypeScript Support - Full type definitions for custom commands
📦 Installation
Option 1: Using npx (Recommended)
# In your project directory
npx cypress-reea-templateOption 2: Install as dependency
npm install --save-dev cypress-reea-template
npx cypress-initOption 3: Clone and modify
git clone <your-repo-url>
cd cypress-reea-template
npm install🎬 Quick Start
Initialize the template (if using npx)
npx cypress-initConfigure your environment
- Update
cypress.config.jswith your base URLs - Set
current_serverto 'dev', 'stage', or 'prod'
- Update
Update credentials
- Edit
cypress/fixtures/user_credentials.json - Edit
cypress/fixtures/email_credentials.json(if using email testing) - Edit
cypress/fixtures/visit_aliases.jsonwith your route aliases
- Edit
Create your first Page Object
npm run addpo LoginPage-BasePageRun Cypress
npm test # Opens Cypress UI npm run test:headless # Runs in headless mode
🏗️ Project Structure
your-project/
├── cypress/
│ ├── e2e/
│ │ └── 000_ExampleSpec.cy.js # Example test spec
│ ├── fixtures/
│ │ ├── user_credentials.json # User login credentials
│ │ ├── email_credentials.json # IMAP email credentials
│ │ └── visit_aliases.json # URL aliases for cy.visit()
│ ├── support/
│ │ ├── commands.js # Custom Cypress commands
│ │ ├── e2e.js # Test setup and imports
│ │ ├── helperFunctions.js # Utility functions
│ │ ├── imap_setup.js # Email testing setup
│ │ └── cmd.d.ts # TypeScript definitions
│ ├── videos/ # Test recordings
│ ├── screenshots/ # Test screenshots
│ └── reports/ # Mochawesome reports
├── PageObjects/ # Your Page Object classes
├── ExamplePageObjects/ # Example PO implementation
│ ├── BaseExample.js
│ └── PageObjectExample.js
├── addpo.js # PO generator script
└── cypress.config.js # Cypress configuration🎨 Page Object Generator
The template includes a powerful CLI tool to generate Page Objects following best practices.
Usage
npm run addpo PageName1,PageName2-BasePage,PageName3-BasePageSyntax
- Comma (
,) - Separates multiple page objects - Dash (
-) - Indicates inheritance (ClassName-BaseClass) - Auto-capitalization -
loginPage→LoginPage
Examples
# Single standalone page
npm run addpo LoginPage
# Single page extending BasePage
npm run addpo LoginPage-BasePage
# Multiple pages (mixed)
npm run addpo LoginPage-BasePage,Dashboard,Settings-BasePageGenerated Structure
Each Page Object includes:
- Constructor with endpoint setup
_navigate()method for page navigation- Example modular methods (
_fillInputField,_clickButton, etc.) - Example parent workflow method
- Full JSDoc documentation
- Method chaining support (
return this)
🔧 Custom Commands
cy.visit() Override - URL Aliases
Visit pages using aliases defined in visit_aliases.json:
// cypress/fixtures/visit_aliases.json
{
"login": {
"endpoint": "/auth/login",
"params": []
},
"dashboard": {
"endpoint": "/admin/dashboard",
"params": [
{ "name": "view", "value": "overview" }
]
}
}
// In your tests
cy.visit('$login') // Visits /auth/login
cy.visit('$dashboard') // Visits /admin/dashboard?view=overviewcy.login() - Session-Based Authentication
Automatically handles login with session caching:
// Login once, session persists across tests
cy.login('admin', 'dev') // Uses credentials from fixtures
// Returns to the current URL after login
// Supports dev, stage, and prod environmentsFeatures:
- Session caching (login once, reuse across tests)
- Automatic environment detection
- Returns to current URL after login
- Configurable via
user_credentials.json
📧 Email Testing
The template includes IMAP integration for email verification workflows.
Setup
- Configure email credentials in
cypress/fixtures/email_credentials.json:
{
"dev": {
"user": "your-user",
"password": "your-password",
"host": "imap.gmail.com",
"port": 993,
"tls": true
}
}- Use in tests:
// Get emails
cy.task('getEmails', {
subject: 'Password Reset',
from: '[email protected]',
since: new Date('2025-10-01'),
limit: 5
}).then((emails) => {
expect(emails).to.have.length.greaterThan(0)
// Process emails...
})
// Delete emails
cy.task('deleteEmails', [email.uid])🛠️ Helper Functions
The template includes 20+ utility functions in cypress/support/helperFunctions.js:
Date & Time
getToday(options)- Get current date with offsetsgetRandomDate()- Generate random future datesgetDaysDifference(date1, date2)- Calculate day differencegetTimestamp(slice, options)- Get timestamp as string or alpha code
String & Data
convertNumericToAlpha(numericString)- Convert numbers to alphabetic codesgenerateStrongPassword(length, options)- Generate secure passwordsjsonToUrlEncoded(obj)- Convert JSON to URL-encoded stringurlEncodedToJson(formDataString)- Parse URL-encoded data
Validation
isOneOf(element, array)- Check array membershipisBetween(value, min, max)- Range validationgetRandomInt(min, max)- Random integer generation
Test Utilities
getCurrentTestOptions(currentTest)- Get test configuration
📊 Reporting
Mochawesome reports are automatically generated after each test run.
# Reports are saved to:
cypress/reports/mochawesome/
# Configuration in cypress.config.js
reporterOptions: {
reportDir: 'cypress/reports/mochawesome',
html: true,
json: true,
embeddedScreenshots: true,
inlineAssets: true
}🌍 Multi-Environment Support
Configure different environments in cypress.config.js:
env: {
current_server: 'dev', // 'dev' | 'stage' | 'prod'
retries: 0,
viewportHeight: 768,
viewportWidth: 1440
}Base URLs are automatically set based on current_server:
- dev: Your dev URL
- stage: Your staging URL
- prod: Your production URL
📝 Writing Tests
Example Test Structure
import { LoginPage } from '../../PageObjects/LoginPage.js'
import { Dashboard } from '../../PageObjects/Dashboard.js'
describe('User Login Flow', () => {
const loginPage = new LoginPage()
const dashboard = new Dashboard()
beforeEach(() => {
cy.login('admin', 'dev')
cy.visit('$dashboard')
})
it('1. should display user dashboard', () => {
dashboard
._navigate()
._waitForDashboardLoad()
// Assertions
cy.url().should('include', '/dashboard')
})
})Page Object Pattern
export class LoginPage extends BasePage {
constructor() {
super('/login')
}
/**
* @info Fills username field
* @chainable
* @modular_method
*/
_fillUsername(username) {
cy.get('[data-testid="username"]')
.should('be.visible')
.clear()
.type(username)
return this
}
/**
* @info Complete login workflow
* @parent_method
* @chainable
*/
login(username, password) {
this
._navigate()
._fillUsername(username)
._fillPassword(password)
._clickSubmit()
return this
}
}🎯 Best Practices
- Use Page Objects - Keep test logic in Page Objects, not specs
- Use Aliases - Define routes in
visit_aliases.json - Session Management - Use
cy.login()for authentication - Modular Methods - Prefix private helpers with
_ - Method Chaining - Always
return thisfor fluent API - Environment Separation - Use different credentials per environment
- Descriptive Tests - Use clear test descriptions with numeric IDs
🔒 Security Notes
- Never commit
*_credentials.jsonfiles (already in.gitignore) - Use environment variables for CI/CD pipelines
- Rotate test account passwords regularly
- Use dedicated test accounts, never production credentials
📚 Advanced Features
Viewport Configuration
// In cypress.config.js
env: {
viewportHeight: 1080,
viewportWidth: 1920
}Test Retries
// Global retries
env: {
retries: 2
}
// Per-test configuration
it('flaky test', { retries: 3 }, () => {
// Test code
})File Upload Support
The template includes cypress-file-upload plugin:
cy.get('input[type="file"]').attachFile('example.pdf')🐛 Troubleshooting
Common Issues
Issue: cy.login() not working
- Check
user_credentials.jsonhas correct structure - Verify
current_servermatches environment in credentials - Check login selectors in
commands.js
Issue: Email testing not working
- Verify IMAP credentials in
email_credentials.json - Enable "Less secure app access" for Gmail
- Check firewall/network allows IMAP port 993
Issue: Page Objects not found
- Ensure correct import path (
../../PageObjects/...) - Check file exists in
PageObjects/directory - Verify class name matches filename
🤝 Contributing
Contributions welcome! Please follow the existing code style and patterns.
📄 License
MIT License - feel free to use in your projects
🙋 Support
For issues, questions, or suggestions:
- Check the example files in
ExamplePageObjects/ - Review the example spec in
cypress/e2e/000_ExampleSpec.cy.js - Read helper function docs in
helperFunctions.js
🎓 Learning Resources
Built with ❤️ by Reea
Happy Testing! 🚀
