πŸš€ Socket Launch Week πŸš€ Day 5: Introducing Socket Fix.Learn More β†’
Socket
Sign inDemoInstall
Socket

cypress-page-object-model

Package Overview
Dependencies
Maintainers
0
Versions
28
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cypress-page-object-model

Cypress Page Object Basic Model ( Ready To Use ) - UI Test Automation Design Pattern for Cypress.io

1.1.2
latest
Source
npm
Version published
Weekly downloads
41
-6.82%
Maintainers
0
Weekly downloads
Β 
Created
Source

Cypress-POM-Ready-To-Use (2024 Edition)

A production-ready Cypress automation framework with Page Object Model, supporting both UI and API testing.

Key Features.

  • TypeScript support with type definitions
  • Page Object Model implementation
  • API testing capabilities with custom commands
  • Parallel test execution
  • CI/CD ready with GitHub Actions
  • Environment-based configuration
  • Comprehensive reporting
  • Built-in retry mechanisms for flaky tests

Quick Start

  • Clone and Install
git clone https://github.com/padmarajnidagundi/Cypress-POM-Ready-To-Use
cd Cypress-POM-Ready-To-Use
  • Setup Project
npm run presetup     # Install all dependencies
npm run setup       # Install Cypress
npm run verify      # Verify Cypress installation
  • Open Cypress
npm run cypress:open  # Open Cypress Test Runner
  • Run Tests
npm run test:ui          # Run UI tests
npm run test:api         # Run API tests
npm run test:parallel    # Run all tests in parallel
npm run test:ci         # Run tests in CI mode

Troubleshooting Installation

If you encounter the error 'cypress' is not recognized as an internal or external command, follow these steps:

  • Clear npm cache and node_modules:
npm cache clean --force
rm -rf node_modules
rm -rf package-lock.json
  • Reinstall dependencies:
npm run presetup
  • Verify installation:
npm run verify
  • Test Cypress:
npm run cypress:open

For QA Engineers

Writing UI Tests

  • Create Page Objects
// cypress/pageObjects/pages/loginPage.ts
import BasePage from '../basePage'

class LoginPage extends BasePage {
    private selectors = {
        username: '#username',
        password: '#password',
        submitBtn: '[data-testid="login-btn"]'
    }

    login(username: string, password: string) {
        this.getElement(this.selectors.username).type(username)
        this.getElement(this.selectors.password).type(password)
        this.getElement(this.selectors.submitBtn).click()
    }
}
  • Write Tests
// cypress/e2e/ui/login.cy.ts
import LoginPage from '../../pageObjects/pages/loginPage'

describe('Login Tests', () => {
    const loginPage = new LoginPage()
    
    beforeEach(() => {
        loginPage.visit('/login')
    })

    it('should login successfully', () => {
        loginPage.login('testuser', 'password')
        // assertions
    })
})

Writing API Tests

  • Use Built-in Commands
// cypress/e2e/api/users.cy.ts
describe('Users API', () => {
    it('should create a new user', () => {
        cy.request({
            method: 'POST',
            url: '/api/users',
            body: {
                name: 'Test User',
                role: 'QA'
            }
        }).then(response => {
            expect(response.status).to.eq(201)
        })
    })
})

Best Practices

  • Selectors

    • Use data-testid attributes: [data-testid="login-button"]
    • Store selectors in page objects
    • Use meaningful selector names
  • Test Organization

cypress/
β”œβ”€β”€ e2e/
β”‚   β”œβ”€β”€ api/           # API Tests
β”‚   β”‚   β”œβ”€β”€ users/
β”‚   β”‚   └── auth/
β”‚   └── ui/            # UI Tests
β”‚       β”œβ”€β”€ login/
β”‚       └── dashboard/
β”œβ”€β”€ pageObjects/
β”‚   β”œβ”€β”€ components/    # Reusable components
β”‚   └── pages/         # Page specific objects
└── fixtures/          # Test data
  • Custom Commands
    • Create reusable commands for common operations
    • Use TypeScript for better type checking
    • Document command parameters

Environment Configuration

// cypress.config.js
module.exports = {
  env: {
    apiUrl: 'https://api.dev.example.com',
    userRole: 'admin',
    featureFlags: {
      newUI: true
    }
  }
}

Running Tests in CI

  • GitHub Actions (pre-configured)
npm run test:ci
  • Jenkins (sample configuration)
pipeline {
    agent any
    stages {
        stage('Test') {
            steps {
                sh 'npm ci'
                sh 'npm run test:ci'
            }
        }
    }
}

Test Reporting

This framework uses Mochawesome for comprehensive HTML reporting. Get detailed insights with screenshots, videos, and test execution metrics.

  • Available Report Commands
npm run report:clean     # Clean previous reports
npm run report:merge     # Merge multiple report JSONs
npm run report:generate  # Generate HTML from JSON
npm run test:report      # Full test execution with reports
  • Report Features

    • Interactive HTML dashboard
    • Test execution timeline
    • Suite and test-level statistics
    • Failure screenshots embedded in report
    • Test execution videos
    • Performance metrics
    • Filter and search capabilities
    • Responsive design for mobile viewing
  • Report Structure

cypress/reports/
β”œβ”€β”€ html/               # HTML reports
β”‚   β”œβ”€β”€ assets/        # Screenshots, videos
β”‚   β”œβ”€β”€ report.html    # Main report
β”‚   └── report.json    # Combined results
└── json/              # Individual test JSONs
  • Reporter Configuration Add these options to cypress.config.js:
module.exports = defineConfig({
  reporter: 'cypress-mochawesome-reporter',
  reporterOptions: {
    charts: true,                    // Enable charts
    reportPageTitle: 'Test Report',  // Custom title
    embeddedScreenshots: true,       // Inline screenshots
    inlineAssets: true,             // Inline assets
    saveAllAttempts: false,         // Save only failures
    reportDir: 'cypress/reports/html',
    overwrite: false,
    html: true,
    json: true
  }
})
  • Viewing Reports

    • Open cypress/reports/html/report.html in any browser
    • Reports are self-contained and can be shared
    • Support offline viewing
    • Can be hosted on any static server
  • CI/CD Integration

- name: Generate Test Report
  if: always()
  run: npm run test:report

- name: Upload Test Report
  if: always()
  uses: actions/upload-artifact@v4
  with:
    name: test-report
    path: cypress/reports/html

Debugging Tips

  • Time Travel

    • Use Cypress Time Travel feature
    • Check screenshots in cypress/screenshots
    • Review videos in cypress/videos
  • Logging

    • Use cy.log() for debug information
    • Enable Chrome DevTools in interactive mode

Contributing

We welcome contributions that help improve this Cypress Page Object Model framework! Here's how you can contribute:

Types of Contributions

  • Page Objects

    • New page object implementations
    • Improvements to existing page objects
    • Utility functions for common actions
  • Test Examples

    • UI test examples
    • API test examples
    • Integration test patterns
  • Documentation

    • Usage examples
    • Best practices
    • Troubleshooting guides

How to Contribute

  • Fork and Clone

    # Fork this repository on GitHub
    git clone https://github.com/YOUR_USERNAME/Cypress-POM-Ready-To-Use.git
    cd Cypress-POM-Ready-To-Use
    npm install
    
  • Create a Branch

    git checkout -b feature/your-feature-name
    
  • Make Changes

    • Follow the existing code structure
    • Add tests for new features
    • Update documentation as needed
  • Contribution Guidelines

    • Use TypeScript for new files
    • Follow the page object pattern
    • Add JSDoc comments for methods
    • Include test cases for new features
    /**
     * Example of a well-documented page object
     */
    class ExamplePage extends BasePage {
      private selectors = {
        submitButton: '[data-testid="submit"]'
      }
    
      /**
       * Submits the form with given data
       * @param {string} data - The data to submit
       * @returns {Cypress.Chainable}
       */
      submitForm(data: string) {
        return this.getElement(this.selectors.submitButton).click()
      }
    }
    
  • Run Tests

    npm run test        # Run all tests
    npm run lint        # Check code style
    npm run build       # Ensure build passes
    
  • Submit PR

    • Create a Pull Request against the main branch
    • Provide a clear description of changes
    • Reference any related issues
    • Wait for review and address feedback

Directory Structure for Contributions

cypress/
β”œβ”€β”€ e2e/                    # Add tests here
β”‚   β”œβ”€β”€ api/               # API test examples
β”‚   └── ui/                # UI test examples
β”œβ”€β”€ pageObjects/           # Add page objects here
β”‚   β”œβ”€β”€ components/        # Reusable components
β”‚   └── pages/            # Page implementations
└── support/              # Add custom commands here
    └── commands/         # Custom command implementations

Code Style Guide

  • Naming Conventions

    • Use PascalCase for page objects: LoginPage.ts
    • Use camelCase for methods: submitForm()
    • Use descriptive test names: 'should successfully submit form'
  • File Organization

    • One page object per file
    • Group related tests in describe blocks
    • Keep selectors in a separate object
  • Testing Standards

    • Write atomic tests
    • Use meaningful assertions
    • Avoid hard-coded waits

Need Help?

  • Check existing issues
  • Join our [Discord community]
  • Read our [documentation]

Support

  • Documentation: See docs/ folder
  • Issues: GitHub Issues
  • Community: [Join our Discord]

FAQ

Common Configuration Issues

  • Error with cypress.config.js

    const { defineConfig } = require('cypress')
    

    Solution: Ensure proper configuration setup:

    • Install browserify preprocessor: npm install @cypress/browserify-preprocessor --save-dev
    • Use the complete configuration:
    const { defineConfig } = require("cypress");
    const createBundler = require("@cypress/browserify-preprocessor");
    
    module.exports = defineConfig({
      viewportWidth: 1920,
      viewportHeight: 1080,
      watchForFileChanges: false,
      // ... other configurations
    });
    
  • TypeScript Support

    • Ensure these dependencies are installed:
    {
      "devDependencies": {
        "@cypress/browserify-preprocessor": "^3.0.2",
        "@types/node": "^20.11.16",
        "typescript": "^5.3.3"
      }
    }
    
  • Running Tests

    • For UI tests: npm run test:ui
    • For API tests: npm run test:api
    • For parallel execution: npm run test:parallel
  • Environment Configuration

    • Default environments are:
      • API URL: https://reqres.in
      • React App URL: https://react-redux.realworld.io
      • Example URL: https://example.cypress.io

Best Practices

  • Page Object Model

    • Keep selectors in page objects
    • Use data-testid attributes
    • Implement base page for common functions
  • Test Organization

    • API tests in cypress/e2e/api/
    • UI tests in cypress/e2e/ui/
    • Integration tests in cypress/e2e/integration/
  • Performance

    • Use cy.session() for login state
    • Enable retries in CI mode
    • Implement proper timeouts

License

MIT License - feel free to use in your projects

Contact

Keywords

cypress

FAQs

Package last updated on 20 Mar 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts