cypress-bootstrapper

1.0.22 • Public • Published

🚀 Cypress Project Bootstrapper

A comprehensive CLI tool for scaffolding Cypress testing projects with advanced features including API testing, schema validation, and CI/CD setup.

Setup

npx cypress-bootstrapper

✨ Features

🎯 Core Functionality

  • Interactive Setup: User-friendly prompts for project configuration
  • TypeScript Support: Optional TypeScript configuration with proper type definitions
  • Multiple Browser Support: Chrome, Firefox, Edge, and Electron
  • Comprehensive Folder Structure: Organized project layout following best practices

🔧 Testing Capabilities

  • UI Testing: Complete E2E testing setup with Page Object Model examples
  • API Testing: Enhanced API testing with cy.api() command
  • Schema Validation: JSON schema validation for API responses using chai-json-schema
  • Swagger/OpenAPI Integration: Individual test files generated from Swagger/OpenAPI specifications
  • 🤖 AI-Powered Test Generation: Generate comprehensive API tests using OpenAI GPT models

📊 Reporting & CI/CD

  • Advanced Reporting: Mochawesome HTML reports with screenshots and videos
  • GitHub Actions: Pre-configured CI/CD workflows
  • Test Artifacts: Automatic screenshot and video capture on failures

🛠 Developer Experience

  • Custom Commands: Pre-built Cypress commands for common operations
  • Test Data Management: Fixtures and test data generation utilities
  • XPath Support: Enhanced element selection with XPath
  • Faker Integration: Realistic test data generation

🚀 Quick Start

Prerequisites

  • Node.js 14+ (18+ recommended)
  • npm or yarn package manager

Installation & Usage

  1. Clone or download the project

    git clone <repository-url>
    cd cypress-bootstrapper
  2. Run the bootstrapper

    node ./bin/bootstrap.js
  3. Follow the interactive prompts

    • Enter your application base URL
    • Choose Git repository initialization
    • Configure GitHub Actions CI/CD
    • Select preferred browser
    • Choose TypeScript usage
    • 📋 Generate traditional API tests from Swagger/OpenAPI (optional)
    • 🤖 Generate AI-powered API tests using OpenAI (optional, requires API key)
  4. Start testing

    # Open Cypress GUI
    npx cypress open
    
    # Run tests headlessly
    npx cypress run

📁 Project Structure

cypress-project/
├── cypress/
│   ├── e2e/
│   │   ├── api/                    # API test files
│   │   │   ├── sample-api.spec.js  # API testing examples
│   │   │   ├── swagger-tests/      # Auto-generated Swagger tests
│   │   │   └── openai-automation/  # 🤖 OpenAI API automation tests
│   │   │       ├── generated/      # AI-generated tests (when OpenAI succeeds)
│   │   │       └── fallback/       # Template specs (when OpenAI fails)
│   │   └── ui/
│   │       ├── pages/              # Page Object Model files
│   │       └── tests/              # UI test files
│   ├── fixtures/
│   │   ├── api-schemas.js          # JSON schema definitions
│   │   └── users.json              # Test data fixtures
│   ├── reports/                    # Test execution reports
│   ├── screenshots/                # Test failure screenshots
│   ├── support/
│   │   ├── commands.js             # Custom Cypress commands
│   │   └── e2e.js                  # Global test configuration
│   └── videos/                     # Test execution videos
├── .github/
│   └── workflows/
│       └── cypress.yml             # GitHub Actions CI/CD
├── cypress.config.js               # Cypress configuration
├── package.json                    # Project dependencies
└── README.md                       # Project documentation

🔧 Configuration

Cypress Configuration

The generated cypress.config.js includes:

  • Base URL configuration
  • Browser preferences
  • Timeout settings
  • Reporter configuration
  • Plugin setup

Environment Variables

Set these in your CI/CD or local environment:

CYPRESS_baseUrl=https://your-app.com
CYPRESS_authToken=your-auth-token

🤖 OpenAI Configuration

When using AI-powered test generation, your OpenAI credentials are securely stored in cypress.env.json:

{
  "OPENAI_API_KEY": "sk-your-api-key",
  "OPENAI_MODEL": "gpt-4o-mini",
  "SWAGGER_URL": "https://automationexercise.com/api/swagger.json"
}

Security Notes:

  • cypress.env.json is automatically added to .gitignore
  • Never commit API keys to version control
  • Get your API key from OpenAI Platform

🧪 Testing Patterns

API Testing Example

describe('API Tests', () => {
  it('should validate API response schema', () => {
    cy.api({
      method: 'GET',
      url: '/api/users/1'
    }).then((response) => {
      expect(response.status).to.eq(200);
      expect(response.body).to.be.jsonSchema(userSchema);
    });
  });
});

🤖 AI-Generated Test Example

The OpenAI integration generates comprehensive tests like this:

describe('AI-Generated API Tests - GET /users', () => {
  it('should successfully retrieve users list', () => {
    cy.api({
      method: 'GET',
      url: '/api/users'
    }).then((response) => {
      expect(response.status).to.eq(200);
      expect(response.body).to.be.an('array');
      expect(response.body[0]).to.have.property('id');
      expect(response.body[0]).to.have.property('name');
      expect(response.body[0]).to.have.property('email');
    });
  });

  it('should handle user not found error', () => {
    cy.api({
      method: 'GET',
      url: '/api/users/999999',
      failOnStatusCode: false
    }).then((response) => {
      expect(response.status).to.eq(404);
      expect(response.body).to.have.property('error');
    });
  });
});

📝 Fallback Test Example

When OpenAI generation fails, the system creates template specs like this:

/**
 * Fallback API Test Spec
 * Generated by Cypress Bootstrapper AI
 *
 * Endpoint: GET /users/{id}
 * Description: Get user by ID
 */

describe('GET /users/{id}', () => {
  const baseUrl = 'https://api.example.com/v1';

  beforeEach(() => {
    // Setup test data and authentication if needed
  });

  it('should successfully get /users/{id}', () => {
    const id = 1;
    cy.api({
      method: 'GET',
      url: `${baseUrl}/users/${id}`,
    }).then((response) => {
      expect(response.status).to.eq(200);
      expect(response.body).to.exist;
      // Add more specific assertions based on your API response
    });
  });

  it('should handle 404 error - Not Found', () => {
    cy.api({
      method: 'GET',
      url: `${baseUrl}/nonexistent-resource`,
      failOnStatusCode: false
    }).then((response) => {
      expect(response.status).to.eq(404);
      expect(response.body).to.have.property('error');
    });
  });

  it('should validate required parameters', () => {
    cy.api({
      method: 'GET',
      url: `${baseUrl}/users/invalid`,
      failOnStatusCode: false
    }).then((response) => {
      expect(response.status).to.be.oneOf([400, 404, 422]);
    });
  });
});

UI Testing with Page Objects

import HomePage from '../pages/HomePage';

describe('UI Tests', () => {
  it('should navigate through the application', () => {
    HomePage
      .visit()
      .verifyPageLoaded()
      .clickAboutLink();
  });
});

📊 Schema Validation

The project includes comprehensive JSON schema validation:

Usage

import { getSchema } from '../fixtures/api-schemas.js';

// Validate response against predefined schema
const schema = getSchema('GET', '/api/users', 200);
expect(response.body).to.be.jsonSchema(schema);

Adding New Schemas

Edit cypress/fixtures/api-schemas.js to add schemas for your API endpoints.

🤖 AI-Powered Test Generation

Overview

The OpenAI integration automatically generates comprehensive API tests using advanced language models. This feature significantly reduces the time needed to create thorough test suites.

Supported Models

  • GPT-4o: Latest and most capable model (recommended for complex APIs)
  • GPT-4o-mini: Fast and cost-effective (recommended for most use cases)
  • GPT-3.5-turbo: Legacy model, budget-friendly option

Features

  • Automatic API Discovery: Analyzes Swagger/OpenAPI specs to discover all endpoints
  • Quota Management: Checks OpenAI API quota and balance before generation
  • Comprehensive Coverage: Generates tests for all HTTP methods (GET, POST, PUT, DELETE, PATCH)
  • Smart Test Generation: Uses API specification details for realistic test scenarios
  • Error Handling: Includes negative test cases and edge conditions based on API responses
  • Schema Validation: Automatically adds response validation using API specification schemas
  • Parameter Validation: Tests all required and optional parameters
  • Graceful Degradation: Creates fallback test specs when OpenAI generation fails
  • Organized Structure: Separate folders for AI-generated and fallback tests
  • Best Practices: Follows Cypress and API testing best practices

Setup Process

  1. Enable during bootstrap: Choose "Yes" when prompted for OpenAI integration
  2. Provide API Key: Enter your OpenAI API key (starts with sk-)
  3. Quota Verification: System automatically checks API quota and balance
  4. Select Model: Choose from available GPT models
  5. Provide Swagger URL: Enter your API's Swagger/OpenAPI JSON URL
  6. Automatic Generation: AI analyzes the API spec and creates comprehensive tests in cypress/e2e/api/openai-automation/

Independent Generation Options

  • 📋 Traditional Swagger Only: Generate tests from Swagger/OpenAPI specification using traditional parsing
  • 🤖 OpenAI Only: Generate AI-powered tests using OpenAI with Swagger context
  • 📋 + 🤖 Both Together: Generate both types of tests for maximum coverage and comparison
  • 🤖 OpenAI without API key: Creates folder structure only for manual test addition later

Separate Configuration

  • Traditional Swagger URL: Used for conventional test generation in swagger-tests/
  • OpenAI Swagger URL: Used for AI analysis and generation in openai-automation/
  • Independent inputs: Each method can use different API specifications

Generated Test Structure

Each endpoint gets comprehensive test coverage:

  • ✅ Successful request scenarios
  • ❌ Error handling (404, 400, 500)
  • 🔍 Response schema validation
  • 🎯 Edge cases and boundary conditions
  • 🔐 Authentication scenarios (when applicable)

Fallback System

When OpenAI generation fails (quota exceeded, network issues, etc.), the system automatically:

  • Always creates folder structure (openai-automation/generated/ and openai-automation/fallback/)
  • Creates template test specs for each endpoint and method (even with basic endpoints if Swagger fails)
  • Includes basic test structure with success and error scenarios
  • Provides parameter validation tests for common scenarios
  • Adds helpful comments for manual completion
  • Organizes fallback tests in separate fallback/ directory
  • Ensures no empty directories - always generates at least basic endpoint specs

Security

  • API keys stored securely in cypress.env.json
  • Environment file automatically added to .gitignore
  • No credentials exposed in generated test files

🔄 CI/CD Integration

GitHub Actions

The generated workflow includes:

  • Automated test execution on push/PR
  • Multi-browser testing support
  • Artifact upload (screenshots, videos, reports)
  • Slack/email notifications (configurable)

Custom CI/CD

For other CI/CD platforms, use:

npm ci
npx cypress run --browser chrome --headless

🛠 Dependencies

Core Dependencies

  • cypress: Testing framework
  • cypress-plugin-api: Enhanced API testing
  • cypress-xpath: XPath selector support
  • cypress-mochawesome-reporter: Advanced reporting
  • chai-json-schema: JSON schema validation
  • faker: Test data generation

🤖 AI Dependencies (Optional)

  • openai: OpenAI API client for AI-powered test generation

Optional Dependencies (TypeScript)

  • typescript: TypeScript compiler
  • @types/cypress: Cypress type definitions
  • ts-node: TypeScript execution

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Submit a pull request

📝 License

This project is licensed under the MIT License.

🆘 Support

For issues and questions:

  1. Check the documentation
  2. Search existing issues
  3. Create a new issue with detailed information

🎯 Roadmap

  • [x] 🤖 AI-powered test generation with OpenAI integration
  • [ ] Support for additional testing frameworks
  • [ ] Enhanced Swagger/OpenAPI schema validation
  • [ ] Visual regression testing integration
  • [ ] Performance testing capabilities
  • [ ] Database testing utilities
  • [ ] AI-powered test maintenance and updates

Readme

Keywords

none

Package Sidebar

Install

npm i cypress-bootstrapper

Weekly Downloads

78

Version

1.0.22

License

ISC

Unpacked Size

108 kB

Total Files

11

Last publish

Collaborators

  • nitpathak