cypress-ai-copilot
v1.4.0
Published
AI-powered Copilot for Cypress automation — generate, debug, and improve tests intelligently.
Maintainers
Readme
🤖 cypress-ai-copilot
AI-powered Copilot for Cypress automation — generate, debug, and improve tests intelligently.
📋 Table of Contents
- Overview
- Installation
- Setup
- Commands
- Usage Examples
- Architecture
- Output Files
- Configuration
- Sample Outputs
- Advanced Features
🎯 Overview
cypress-ai-copilot is a production-ready Cypress plugin that integrates OpenAI's GPT-4o into your test automation workflow. It provides:
| Feature | Command | Description |
|---|---|---|
| 🔍 Failure Analyzer | cy.aiAnalyzeFailure() | AI-powered root cause analysis for test failures |
| 📝 Test Generator | cy.aiGenerateTest() | Generate tests from plain English descriptions |
| 🐛 Bug Reporter | cy.aiGenerateBugReport() | Professional JIRA/GitHub-ready bug reports |
| 🩹 Selector Healer | cy.aiHealSelector() | Auto-suggest stable selectors for broken ones |
| 🔄 Sync Validator | cy.aiSyncCheck() | Compare UI values against API response data |
| 🔧 Maintenance Advisor | cy.aiSuggestImprovements() | Code quality review and improvement suggestions |
| ⚡ Smart Get | cy.aiGet(selector) | ONE-RUN PASS: Heals element and fixes source code simultaneously |
| 🧙 Global Healing | cy.get(selector) | ZERO-TOUCH PASS: Standard cy.get now heals automatically in Run 1! |
📦 Installation
To install in your current project:
npm install cypress-ai-copilot --save-devGlobal / Multi-project Usage: You can install the package globally to access the CLI generator from anywhere.
npm install -g cypress-ai-copilot🛠️ CLI Setup (Interactive)
If you have installed the package globally (or via npx locally), you can scaffold the necessary files instantly:
npx cypress-ai-copilot initThis generates the .env template to add your your OpenAI key.
You can also check connectivity:
npx cypress-ai-copilot verifyTo see how to activate the AI Auto-Fix mode:
npx cypress-ai-copilot fix🚀 Step-by-Step Guide for Any Project
Here is exactly how to install and activate the AI Copilot inside an existing Cypress project.
Step 1: Install the Plugin
Open your terminal in the root of your Cypress project and install the package:
npm install cypress-ai-copilot --save-devStep 2: Generate Configuration (CLI)
Run the built-in setup command to instantly scaffold the necessary configuration:
npx cypress-ai-copilot initThis will automatically create a .env file in your project.
Open the newly created .env file and paste in your OpenAI API Key:
OPENAI_API_KEY=sk-proj-your-api-key-here
AI_MODEL=gpt-4oStep 3: Register Plugin in cypress.config.js
Open your cypress.config.js (or .ts) file. Load the plugin inside the setupNodeEvents function.
const { defineConfig } = require('cypress');
// 1. Import the AI Copilot
const setupCypressAICopilot = require('cypress-ai-copilot');
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
// 2. Initialize the AI Copilot within your Node environment
setupCypressAICopilot(on, config);
return config;
}
},
env: {
// Optional: Auto-run AI analysis whenever a test fails
AI_AUTO_ANALYZE: true
}
});Step 4: Add Custom Commands in Support File
To inject the cy.ai* commands into your browser context, open your E2E support file (usually cypress/support/e2e.js or cypress/support/index.js) and add this line inside:
If using import (ESM):
import 'cypress-ai-copilot/support';If using require (CJS):
require('cypress-ai-copilot/support');Step 5: Write Your First AI Test!
Create a new spec file (cypress/e2e/ai-test.cy.js) and try out an AI command:
describe('My First AI Test', () => {
it('should heal a broken selector automatically', () => {
cy.visit('https://example.cypress.io');
// Simulating a broken selector by asking the AI for a better one!
cy.aiHealSelector('.non-existent-utility-class', {
elementDesc: 'The big "Querying" link on the homepage'
}).then((healedSelector) => {
cy.log('The AI suggested:', healedSelector);
cy.get(healedSelector).click();
});
});
});Run npx cypress open and watch it work!
Step 6: Activate AI Auto-Healing (Fix Mode)
To let the AI automatically rewrite your failing code files on the fly, run your tests from the terminal with the AI_AUTO_FIX flag:
npx cypress run --env AI_AUTO_FIX=true🪄 How AI Auto-Healing Works (The Cycle)
The AI Copilot doesn't just report errors; it evolves your code. Here is the standard workflow for a broken test:
- Test Fails: You run a test (e.g.
npx cypress run --spec "my-test.cy.js" --env AI_AUTO_FIX=true). - AI Detects Failure: The plugin catches the crash, reads the error, and captures a screenshot of the DOM.
- AI Rewrites Code: OpenAI analyzes your entire source file and generates a fix (updating a broken selector, fixing a bad assertion, or adding a missing step).
- File Overwritten: The plugin instantly overwrites your local file on disk with the healed code.
- Next Run = Green: You run the test again, and it passes perfectly!
[!TIP] Why two runs? Cypress loads your test code into memory at the start. When the AI rewrites your file on disk, the memory still has the old broken code. The second run loads the fresh, fixed code from disk.
⚡ Dynamic vs. Permanent Healing
| Feature | Dynamic Healing (cy.aiHealSelector) | Permanent Healing (AI_AUTO_FIX) |
|---|---|---|
| Goal | Make the test pass right now | Fix the source code forever |
| Passes on: | Run 1 | Run 2 |
| Use Case | Flaky elements, dynamic IDs | Broken code, syntax errors, bad logic |
| Action | Returns a string in memory | Overwrites your .cy.js file |
🚀 Global One-Run-Pass (Version 1.3.0)
In version 1.3.0, you don't even need to use cy.aiGet. Normal cy.get() calls now automatically heal themselves in the FIRST run whenever AI_AUTO_FIX=true is enabled!
- No code changes required: Use your existing
cy.get(). - Self-Heals dynamically: If an element is missing, AI finds it.
- Fixes source code: Overwrites your
.cy.jsfile with the fixed selector. - Passes instantly: The test continues and completes in Run 1.
🎯 Verification Guide (Test Each Feature)
Use these snippets to verify everything is working properly in your project.
1. Verify Failure Analysis
Create a test that is guaranteed to fail:
it('fails at a specific step', () => {
cy.visit('https://example.cypress.io');
cy.get('#element-does-not-exist').click(); // Crash here
});Command: npx cypress run
Check: Open reports/ai-failure.json to see the AI's diagnosis.
2. Verify Auto-Fixer (Killer Feature)
Create a test with a bad CSS selector (syntax error):
it('has a broken selector', () => {
cy.visit('https://example.cypress.io');
// AI should fix the trailing ">" automatically
cy.get('#productTable>tbody>tr>').should('have.length', 5);
});Command: npx cypress run --env AI_AUTO_FIX=true
Check: Open the file in your code editor. You will see the AI has removed the invalid > and fixed the code!
3. Verify Selector Healing
it('heals a selector', () => {
cy.visit('https://google.com');
cy.aiHealSelector('.non-existent-search-bar', {
elementDesc: 'Google main search input'
}).then(selector => cy.get(selector).type('AI Testing'));
});Check: The AI will dynamically find the correct selector like [name="q"] and type into it.
🧩 Commands
cy.aiAnalyzeFailure(context?)
Analyzes a Cypress test failure using OpenAI. Outputs a structured JSON report.
cy.aiAnalyzeFailure()
// With context override:
cy.aiAnalyzeFailure({
testName: 'Login Test',
failedStep: "cy.get('#login-button').click()",
errorMessage: "Timed out retrying after 4000ms",
selector: '#login-button',
domSnippet: '<div>...your DOM...</div>'
})Returns:
{
"summary": "Login button not found due to changed selector",
"root_cause": "The selector '#login-button' was changed to data-test='login-button'",
"fix": "Update selector to: cy.get('[data-test=\"login-button\"]')",
"impact": "All login-dependent tests will fail",
"confidence": "High",
"category": "selector_issue"
}cy.aiGenerateTest(userStory, options?)
Generates a complete Cypress test + BDD Gherkin scenario from a natural language description.
cy.aiGenerateTest('User logs in and adds product to cart', {
baseUrl: 'https://www.saucedemo.com',
framework: 'React',
authType: 'Session Cookie'
})Output files:
generated/ai-test.cy.jsgenerated/ai-test.feature
cy.aiGenerateBugReport(context?)
Generates a professional bug report from the current test failure.
cy.aiGenerateBugReport({
testName: 'Checkout Price Validation',
errorMessage: 'expected "$29.99" to equal "$30.00"',
url: 'https://myapp.com/cart',
browser: 'Chrome 121'
})Output files:
reports/ai-bug-report.txt(JIRA/GitHub paste-ready)reports/ai-bug-report.json
cy.aiHealSelector(failedSelector, options?)
Suggests a stable CSS selector to replace a broken one. Automatically captures current DOM.
// Auto DOM capture
cy.aiHealSelector('.btn.btn-primary.mt-3').then((healed) => {
cy.get(healed).click()
})
// With manual context
cy.aiHealSelector('#broken-id', {
elementDesc: 'Submit button on checkout form',
domSnippet: '<button data-testid="checkout-submit">Checkout</button>'
})Returns: The healed selector string (e.g. [data-testid='checkout-submit'])
cy.aiSyncCheck({ api, ui, endpoint?, page? })
Compares API response data against UI-rendered values field by field.
const apiResponse = {
name: 'Sauce Labs Backpack',
price: 29.99,
inStock: true
}
cy.aiSyncCheck({
api: apiResponse,
ui: {
name: 'Sauce Labs Backpack',
price: '$31.99', // Intentional mismatch
inStock: 'true'
},
endpoint: '/api/v1/product/backpack',
page: '/inventory.html'
}).then((result) => {
expect(result.result.overall_status).to.equal('FAILED')
})Returns: Detailed mismatch report with field-by-field comparison.
cy.aiSuggestImprovements(options?)
Reviews your test code for quality issues, anti-patterns, and improvement opportunities.
// Auto-reads current spec file
cy.aiSuggestImprovements()
// With custom code
cy.aiSuggestImprovements({
testCode: myTestCode,
testFile: 'checkout.cy.js'
}).then((result) => {
console.log(`Quality Score: ${result.result.overall_quality_score}/100`)
console.log(`Grade: ${result.result.grade}`)
})Detects:
- ⏱ Hard waits (
cy.wait(3000)) - 💣 Brittle selectors (
.mt-4,.p-2,button, etc.) - 🔁 Duplicate steps across tests
- ❌ Missing assertions
- 📦 Missing abstraction / Page Objects
cy.aiAutoFixTest(options?)
(Killer Feature) — Reads your failing test file directly from disk, passes the source code and the exact failure message to OpenAI, re-writes your test code to fix the bug, and overwrites your .cy.js file on disk so it passes on the next run!
// Automatically fixes the currently running test file!
cy.aiAutoFixTest({
errorMessage: 'Timed out retrying: expected to find element: #old-id',
testName: 'Login Form Submission'
})Returns: The fully healed test code, and instantly saves the fixed .cy.js file to your project.
cy.aiGet(selector, options?)
Ultimate One-Run Pass Command. Tries to find the element, and if it fails, it heals it with AI, continues the test immediately, AND permanently fixes your source code on disk (if AI_AUTO_FIX=true).
// Instead of cy.get('.broken-btn').click()
cy.aiGet('.broken-btn').click() 🕹️ Feature Setup & Execution Guide
Follow these steps to ensure every AI feature works correctly in your project.
1. AI Failure Analyzer
- Scenario: A test fails due to a bug or changed UI.
- Setup: Ensure
setupCypressAICopilot(on, config)is in your config. - Execution: Run any failing test. The analyzer triggers automatically via the
afterEachhook. - Result: Check
reports/ai-failure.jsonfor root cause analysis.
2. AI Test Generator
- Scenario: You need to create a new test but don't want to code from scratch.
- Execution: Call
cy.aiGenerateTest('description')in a spec file. - Result: New files appear in
generated/ai-test.cy.jsandgenerated/ai-test.feature.
3. AI Bug Reporter
- Scenario: You found a bug and need to report it to JIRA.
- Execution: Call
cy.aiGenerateBugReport()in your test. - Result: A professional summary is saved to
reports/ai-bug-report.txt.
4. AI Selector Healer
- Scenario: A button selector broke after a UI update.
- Execution: Wrap your click in the healer:
cy.aiHealSelector('.old-btn').then(newS => cy.get(newS).click()). - Result: The test passes by dynamically finding the new button location.
5. AI UI/API Sync Validator
- Scenario: Your frontend is showing $30 but the database/API says $25.
- Execution: Pass your API and UI objects to
cy.aiSyncCheck({ api, ui }). - Result: Check
reports/ai-sync.jsonfor a field-by-field mismatch report.
6. AI Maintenance Advisor
- Scenario: Your test suite is getting slow or brittle.
- Execution: Call
cy.aiSuggestImprovements(). - Result: Check
reports/ai-maintenance.jsonfor your "Quality Score" and code cleanup tips.
7. AI Auto-Fixer (Fix Mode)
- Scenario: You want your tests to fix themselves while you drink coffee.
- Execution: Run Cypress from CLI with:
npx cypress run --env AI_AUTO_FIX=true. - Result: Any failing
.cy.jsfiles are physically rewritten on your disk with working code.
8. AI Smart Get (One-Run Pass)
- Scenario: You want the test to pass today AND be fixed for tomorrow in one single execution.
- Execution: Replace
cy.get()withcy.aiGet(). - Result: The test bypasses the broken selector, clicks the right element, and updates your file in the background.
🏗 Architecture
cypress-ai-copilot/
│
├── src/
│ ├── openai/
│ │ ├── openaiClient.js # Singleton OpenAI client + retry logic
│ │ └── prompts/
│ │ ├── failurePrompt.js # Failure analysis prompt templates
│ │ ├── testPrompt.js # Test generation prompt templates
│ │ ├── bugPrompt.js # Bug report prompt templates
│ │ ├── selectorPrompt.js # Selector healing prompt templates
│ │ ├── syncPrompt.js # UI/API sync validation prompts
│ │ └── maintenancePrompt.js # Code maintenance advisor prompts
│ │
│ ├── plugin/
│ │ ├── index.js # Plugin entry + all 6 AI feature handlers
│ │ └── index.d.ts # TypeScript declarations
│ │
│ ├── commands/
│ │ └── aiCommands.js # All 6 Cypress custom commands
│ │
│ └── utils/
│ ├── parser.js # Safe JSON parsing + result envelope
│ └── normalizer.js # Value normalization for sync comparison
│
├── cypress/
│ ├── support/
│ │ ├── commands.js # Imports AI commands
│ │ └── e2e.js # Global support + afterEach auto-analysis hook
│ └── e2e/
│ ├── ai-copilot-demo.cy.js # Full feature showcase tests
│ └── saucedemo-ai.cy.js # Real-world SauceDemo integration tests
│
├── reports/ # AI-generated JSON + text reports
├── generated/ # AI-generated Cypress test files
├── cypress.config.js # Cypress config with plugin setup
├── .env # API keys and model config
└── package.jsonData Flow
Cypress Test
│
▼
cy.ai*() Command (browser context)
│
▼
cy.task('aiCallOpenAI') (bridge to Node.js)
│
▼
Plugin Index (feature router)
│
▼
Prompt Builder → OpenAI API (GPT-4o)
│
▼
JSON Response Parser
│
├──► Disk (reports/*.json, generated/*.cy.js)
└──► Cypress Log + Return value📊 Output Files
| File | Description |
|---|---|
| reports/ai-failure.json | Failure analysis with root cause and fix |
| reports/ai-bug-report.json | Structured bug report data |
| reports/ai-bug-report.txt | JIRA/GitHub paste-ready plain text |
| reports/ai-selector.json | Healed selector with confidence score |
| reports/ai-sync.json | UI vs API field comparison results |
| reports/ai-maintenance.json | Code quality score and improvement suggestions |
| reports/ai-test-generation.json | Test generation metadata |
| generated/ai-test.cy.js | AI-generated Cypress test file |
| generated/ai-test.feature | AI-generated BDD Gherkin scenario |
⚙️ Configuration
| Environment Variable | Default | Description |
|---|---|---|
| OPENAI_API_KEY | (required) | Your OpenAI API key |
| AI_MODEL | gpt-4o | OpenAI model to use |
| AI_MAX_TOKENS | 4096 | Maximum tokens per response |
| AI_TEMPERATURE | 0.7 | Response creativity (0=deterministic, 1=creative) |
| AI_AUTO_ANALYZE | true | Auto-run failure analysis after each failed test |
📄 Sample Outputs
Failure Analysis (reports/ai-failure.json)
{
"feature": "failure_analysis",
"generated_at": "2026-03-20T10:30:00.000Z",
"plugin": "cypress-ai-copilot",
"result": {
"summary": "Login button selector changed from ID to data-test attribute",
"root_cause": "Developer refactored the login button from id='login-button' to data-test='login-button'",
"fix": "Update test: cy.get('[data-test=\"login-button\"]').click()",
"impact": "All 12 login-dependent tests will fail in CI",
"confidence": "High",
"category": "selector_issue"
}
}Selector Heal (reports/ai-selector.json)
{
"feature": "selector_healing",
"result": {
"new_selector": "[data-testid='login-btn']",
"confidence": "93%",
"selector_type": "data-testid",
"explanation": "data-testid attributes are specifically intended for testing",
"alternatives": [
{ "selector": "[aria-label='Login']", "confidence": "85%" },
{ "selector": "#login-btn", "confidence": "72%" }
]
}
}Sync Check (reports/ai-sync.json)
{
"feature": "sync_validation",
"result": {
"overall_status": "FAILED",
"local_comparison": {
"mismatches": [
{ "field": "price", "api_value": 29.99, "ui_value": "$31.99", "status": "FAILED", "severity": "High" }
],
"matched": [
{ "field": "name", "value": "Sauce Labs Backpack", "status": "PASSED" }
]
}
}
}🚀 Advanced Features
Auto Failure Analysis
Automatically triggered after every failed test via afterEach. Control with:
// cypress.config.js
env: { AI_AUTO_ANALYZE: false } // Disable
// or cypress.env.json
{ "AI_AUTO_ANALYZE": false }TypeScript Support
Full IntelliSense via src/plugin/index.d.ts. Add to tsconfig.json:
{
"include": ["node_modules/cypress-ai-copilot/src/plugin/index.d.ts"]
}Chaining Commands
cy.aiHealSelector('#broken-btn').then((healed) => {
cy.get(healed).should('be.visible').click()
})
cy.aiAnalyzeFailure().then((analysis) => {
cy.aiGenerateBugReport({ errorMessage: analysis.result.root_cause })
})🛠️ Troubleshooting
"npm error Conflicting peer dependency" when installing
If you see a peer dependency conflict regarding Cypress (e.g. from @4tw/cypress-drag-drop or cypress-axe), this means your current project has packages that require conflicting versions of Cypress.
To bypass this and install the plugin anyway, run:
npm install cypress-ai-copilot --save-dev --legacy-peer-deps🤝 Author
Saran M V | Senior QA Architect
Built with ❤️ using Cypress + OpenAI GPT-4o
📜 License
MIT © 2026 cypress-ai-copilot contributors
