Prompt file imported from jordasvs/playwright-mcp-copilot-agent (
.github/prompts/generate_test_ui.prompt.md). Fill in{{name}},{{error_message}}before use. Copyright stays with the author.
๐ค Agent Instructions Prompt
๐ก๏ธ Ultra-Rigid Agent Instructions Prompt
FIRST ACTION IN ANY NEW CHAT
Before performing any action, read this file completely, understand all steps, and follow the strict workflow: Data โ Selectors โ Page Objects โ Fixture โ Spec. Proceed efficiently, validating each step autonomously and explicitly confirming the completion of each step before proceeding.
๐จ CRITICAL RULES ๐จ
- โ Never generate
.spec.jsbefore completing all previous layers. - โ Never skip steps in the sequence.
- โ Never create files out of order.
- โ Each layer must be fully implemented and automatically validated before proceeding.
- โ Confirmation is required after each step (
โ STEP COMPLETE), but the process should be autonomous. - ๐ Page Objects must import selectors from the existing selectors only.
- ๐ Fixtures must import only Page Objects from pages layer.
- ๐ Specs must use fixture-injected Page Objects and ONLY ASSERTION data from
data/. - โก All validations must be done automatically without creating separate validation files.
- ๐ค The agent should act autonomously in browser interactions using MCP Playwright.
๐ STEP-BY-STEP GENERATION WORKFLOW
๐ STEP 1: DATA LAYER (data/)
Generate all test data as JSON files, separating functional data from assertion data. Example: myFeature.json
{
"functionalData": {
"credentials": {
"username": "user123",
"password": "pass123"
},
"inputValues": {
"field1": "value1",
"field2": "value2"
}
},
"assertionData": {
"expectedResults": {
"message": "Success message",
"status": "completed",
"count": 5
},
"errorScenarios": {
"invalidLogin": "Invalid credentials",
"emptyFields": "Required fields"
}
}
}
โ
Confirm completion before moving to Step 2.
โ Do not generate Selectors, Page Objects, Fixture, or Specs yet.
๐ STEP 2: SELECTORS LAYER (selectors/)
Generate selectors based only on the data layer. Group by context (menu, form, notifications). Example: export const selectors = { pageName: { component: { element: 'reliable-selector', button: '[data-testid="button"]', input: '.specific-class input' } } };
๐ CRITICAL: SELECTOR VALIDATION
After creating the selectors, you MUST validate them automatically before proceeding:
- Automatically navigate to the application using MCP Playwright tools
- Verify each selector and confirm it matches the intended element
- Adapt selectors if necessary based on the actual page structure
- Use reliable attributes (data-testid is preferred when available)
Example of automated validation process:
// Function to validate selectors automatically
async function validateSelectors(page, selectors) {
// Navigate to the page
await page.goto(url);
// Validate each crucial selector
for (const [name, selector] of Object.entries(selectors)) {
try {
const element = await page.$(selector);
const isVisible = await element.isVisible();
console.log(`Selector {{name}}: ${isVisible ? 'Valid' : 'Visibility issue'}`);
// Adjust selector if needed
if (!isVisible) {
// Logic to find an alternative selector
}
} catch (error) {
console.error(`Selector {{name}} invalid: {{error_message}}`);
// Implement automatic selector correction
}
}
}
IMPORTANT: Do not create separate validation files. Incorporate adjustments directly into the selectors file.
โ Validate all selectors automatically and proceed to Step 3. โ Do not generate Page Objects, Fixture, or Specs until all selectors are validated, but do not create separate validation files.
๐ STEP 3: PAGE OBJECTS (pages/)
โ ๏ธ CRITICAL: Before creating any new Page Object method:
-
VALIDATION OF EXISTING METHODS: a. FIRST: Read and understand all available methods in basePage.js b. SECOND: Check methods in all existing pages in the pages/ directory c. THIRD: Create a map of identified reusable methods
-
ANALYSIS DOCUMENTATION:
// Map of Existing Methods: // BasePage: // - click() - for clicking elements // - fill() - for filling inputs // - etc... // // LoginPage: // - login() - already handles the complete login flow // - isDashboardVisible() - checks dashboard visibility // - etc... // // OtherPages: // - list relevant methods... -
IMPLEMENTATION DECISION: a. REUSE existing methods when possible b. EXTEND existing methods if necessary c. CREATE new methods ONLY if demonstrably necessary
-
IF CREATING A NEW METHOD: a. Document why existing methods do not meet the requirements b. Explain the specific need for the new method c. Ensure there is no duplication of functionality
-
CHECKLIST BEFORE IMPLEMENTATION: [ ] Mapping of existing methods complete [ ] Reuse analysis performed [ ] Decision documentation included [ ] Duplication verification completed
-
FUNCTIONAL DATA IMPORT: a. Import FUNCTIONAL data from Step 1 (data/) to perform operations b. Example: login credentials, form field values, etc.
Implementation example after complete analysis:
import BasePage from './basePage'; import { selectors } from '../selectors/myFeatureSelectors'; import testData from '../data/myFeature.json'; // Import of functional data
export default class MyFeaturePage extends BasePage { constructor(page) { super(page); }
// MAP OF ANALYZED EXISTING METHODS:
// BasePage:
// - this.click() - used for clicks
// - this.fill() - used for inputs
// - this.isVisible() - used for validations
//
// LoginPage:
// - login() - already handles the complete login flow
// - isDashboardVisible() - checks dashboard visibility
//
// OtherPages:
// - list relevant methods...
// NEW METHODS (Justification for each):
/**
* @description Performs a specific action not covered by existing methods
* @throws {Error} When the element is not available
*
* JUSTIFICATION FOR NEW METHOD:
* 1. Checked basePage.js: has no similar method
* 2. Checked loginPage.js: has no related functionality
* 3. Checked otherPages: no reusable method found
* 4. Specific need: [describe the need]
*/
async someNewAction() {
// Uses functional data imported from data file
await this.fill(selectors.pageName.component.input, testData.testCase.testData.field1);
await this.click(selectors.pageName.component.button);
}
} โ Confirm completion before moving to Step 4. โ Do not generate Fixture or Specs yet.
๐ STEP 4: FIXTURE (fixture/)
Register new Page Objects in fixture.js. Import only Page Objects from Step 3. Example:
import { test as base } from '@playwright/test';
import MyFeaturePage from '../pages/myFeaturePage';
const test = base.extend({
myFeaturePage: async ({ page }, use) => {
await use(new MyFeaturePage(page));
}
});
export default test;
โ
Confirm completion before moving to Step 5.
โ Do not generate Specs yet.
๐งช STEP 5: SPEC FILES (tests/)
Generate .spec.js files only after Step 4 confirmation. Must use fixture-injected Page Objects and import ONLY ASSERTION data from the data layer (Step 1). No direct selectors or hardcoded values.
๐ CRITICAL: Tests MUST follow the AAA pattern (Arrange, Act, Assert)
Each test should have clear sections with comments:
- Arrange & Act: Setup test environment and execute actions
- Assert: Validate the expected results using assertion data imported from data files
Example:
import test, { expect } from '../fixture/fixture';
import testData from '../data/myFeature.json'; // Import ONLY assertion data
test.describe('Feature Tests', () => {
test('Should perform action - Description of test purpose', async ({ myFeaturePage }) => {
// Arrange & Act
await myFeaturePage.navigateToPage();
await myFeaturePage.someAction(); // Functional data is already encapsulated in the Page Object
// Assert
const result = await myFeaturePage.getResult();
expect(result).toBe(testData.testCase.expectedOutput); // Using only assertion data
});
test('Should handle error condition - Description of test purpose', async ({ myFeaturePage }) => {
// Arrange & Act
await myFeaturePage.navigateToPage();
await myFeaturePage.performActionWithError(); // Functional data is already encapsulated in the Page Object
// Assert
const errorMessage = await myFeaturePage.getErrorMessage();
expect(errorMessage).toContain(testData.errorCase.expectedError); // Using only assertion data
});
});
โ Confirm Specs complete.
๐ DIRECTORY STRUCTURE
projeto/
โโโ data/
โ โโโ myFeature.json ๐ [STEP 1]
โโโ selectors/
โ โโโ myFeatureSelectors.js ๐ [STEP 2]
โโโ pages/
โ โโโ basePage.js
โ โโโ myFeaturePage.js ๐ [STEP 3]
โโโ fixture/
โ โโโ fixture.js ๐ [STEP 4]
โโโ tests/
โโโ myFeature.spec.js ๐งช [STEP 5]
CONFIRMATION RULES
After completing each step, the agent must output: โ STEP COMPLETE: <layer_name> Only then may it proceed to the next step. If a step is incomplete, do not proceed. Everything should be done autonomously without requiring unnecessary manual user intervention for validation.
FINAL NOTES
Respect folder structure. Follow strict sequential workflow: Data โ Selectors โ Page Objects โ Fixture โ Spec. Ensure maximum encapsulation and reuse. Never generate a spec before confirming all prior layers.
Automated Handling of Gherkin Scenarios
- The agent will receive test scenarios written in Gherkin format (
Given / When / Then). - Each step in the Gherkin scenario must be automatically mapped to actions in the Page Objects.
For each step:
- Use data from
data/. - Use selectors from
selectors/. - Use page methods from
pages/.
If a step requires elements or logic not yet implemented:
- Add selectors to
selectors/automatically. - Add or extend the page object in
pages/without manual intervention. - Register the page in
fixture/autonomously.
Only after all mappings are complete:
- Generate the Playwright test in JavaScript (
@playwright/test) insidetests/. - Execute page interactions autonomously, without requiring manual approval for each browser interaction.
- Automate the entire validation process without creating intermediate validation files.
Base Configuration
- All tests use the base URL defined in
utils.js. - The base URL for the application is stored in the
baseUrlconstant.
Code Style
- Follow clean code best practices.
- Use descriptive and consistent names for files and methods.
- Avoid duplication โ always reuse existing logic in
basePage.jsor already created pages.
Validation Checklist
Before completing each step, verify:
Data Files (Step 1)
- Created in
data/folder - Uses .json extension
- Contains all test data needed (functional and assertion)
- No sensitive data included
- Functional data separated from assertion data
Selectors (Step 2)
- Created in
selectors/folder - Properly grouped by context
- No duplicated selectors
- Clear, descriptive names
- Automatically validated against actual DOM structure
- Selectors adjusted as needed
- Reliable attributes used (data-testid preferred)
- Added specificity for ambiguous elements
Page Objects (Step 3)
- Extends BasePage
- Imports selectors from selector file
- Imports FUNCTIONAL data from data files
- NO hardcoded selectors
- NO hardcoded functional data
- Methods are atomic and reusable
Fixture (Step 4)
- Page properly registered
- Follows existing pattern
- No duplicate registrations
Specs (Step 5)
- Uses fixture
- Imports ONLY ASSERTION data from data files
- NO hardcoded values
- NO direct selectors
- NO import of functional data (already in Page Objects)
- Follows AAA pattern (Arrange & Act, Assert)
- Includes descriptive test names with purpose
- Contains AAA comments to mark sections
- Groups related tests with test.describe()
Only proceed to the next step when all checkboxes are checked for the current step.
Performance Validation
Before finalizing any test implementation, ensure:
Performance Checklist
- Use optimized selectors (prefer data-testid over generic CSS classes)
- Implement appropriate wait strategies
- Use explicit waits for specific conditions
- Avoid fixed timeouts when possible
- Document when implicit waits are necessary
- Validate loading times and timeout configurations
- Document acceptable response time thresholds
- Implement performance assertions when relevant
- Consider test execution time optimization
Error Handling
Implement robust error handling across all layers:
Error Handling Guidelines
- Define retry strategies for flaky actions
async retryAction(action, maxAttempts = 3) { for (let attempt = 1; attempt <= maxAttempts; attempt++) { try { await action(); return; } catch (error) { if (attempt === maxAttempts) throw error; await this.page.waitForTimeout(1000 * attempt); } } } - Implement descriptive error messages
- Configure screenshot/video capture on failure
- Handle dynamic element behavior
- Define recovery procedures for common failures
๐ Code Standards & Documentation
Selector Best Practices
Follow these guidelines when creating selectors:
-
Selector Priority (in order of preference):
data-testidattributes (most reliable)- Unique ID attributes
- ARIA attributes (role, label)
- Unique attributes (name, placeholder)
- CSS classes (only if stable and unique)
- Tag names + context (least reliable, last resort)
-
Selector Structure:
- Always add context for ambiguous elements (
.parent .elementinstead of just.element) - Use parent containers to narrow scope:
.specific-section .buttonoverbutton - For critical UI elements, use compound selectors:
button[type="submit"][data-testid="login"]
- Always add context for ambiguous elements (
-
Automated Selector Validation Process:
// Example of automated validation workflow async function validateSelectorsAutomatically() { // 1. Navigate to the page await page.goto(url); // 2. Validate all critical selectors in a single pass const results = {}; for (const [key, selector] of Object.entries(selectors)) { try { const el = await page.$(selector); results[key] = { found: !!el, visible: el ? await el.isVisible() : false, enabled: el ? await el.isEnabled() : false }; // Automatic adjustments if needed if (!results[key].found) { // Try alternative selection strategies } } catch (e) { results[key] = { error: e.message }; } } return results; }
Method Documentation
Follow this template for all new methods:
/**
* @description What the method does
* @param {type} paramName - Parameter description
* @returns {type} - Return value description
* @throws {ErrorType} - When and why it throws
* @example
* await page.methodName('parameter');
*/
Naming Conventions
File Naming
- Data Files:
featureName.json - Selectors:
featureNameSelectors.js - Page Objects:
FeatureNamePage.js - Test Files:
featureName.spec.js
Method Naming
- Actions: use verb + noun (e.g.,
submitForm()) - Getters: use get + noun (e.g.,
getErrorMessage()) - Validations: use is/has + condition (e.g.,
isElementVisible())
Test Prerequisites and Setup
Ensure proper test setup:
Setup Checklist
- Define required initial state
- Document external dependencies
- Specify required test data
- Establish execution order when necessary
- Implement proper cleanup procedures
- Configure environment-specific requirements
๐ AAA Pattern Rules & Benefits
All test files must strictly follow the Arrange-Act-Assert (AAA) pattern:
- Arrange: Set up the test environment and prerequisites
- Act: Execute the functionality being tested
- Assert: Verify the expected outcomes
Benefits:
- Clear separation of test responsibilities
- Easier to understand test flow
- Improved maintainability and readability
- Simplified debugging when tests fail
- Consistent test structure across the codebase
Requirements:
- Use comments to clearly mark the sections (
// Arrange & Actand// Assert) - Keep assertions separate from setup and actions
- Each test should focus on testing a single behavior
- Group related tests using test.describe()
- Use data from data files, never hardcode test values
- Provide descriptive test names that explain what is being tested
๐ Systematic Error Analysis Approach
When tests fail, follow this rigorous approach to analyze and resolve issues:
1๏ธโฃ Error Identification Process
Step 1: Collect Error Information
- Identify the error message and type (timeout, assertion failure, element not found, etc.)
- Note which test step was executing when the failure occurred
- Document which environment/browser the failure occurred in
Step 2: Analyze Error Artifacts
- Review test-results directory for the specific failed test
- Examine error-context.md to understand the page state at failure time
- Review screenshot/video evidence if available
- Analyze trace files using
npx playwright show-trace
Step 3: Structured Diagnosis
- Create a table mapping expected vs. actual application state:
| Component | Expected | Actual | Discrepancy |
|------------------|-------------------------|------------------------|-----------------------|
| Login Form | Should be visible | Is visible | None |
| Username Field | Should accept input | Not found | Selector mismatch |
| Error Message | Should display text | No text displayed | Timing/state issue |
Step 4: Root Cause Analysis
- Compare the page snapshot from error-context.md with defined selectors
- Verify if the application structure matches your selector assumptions
- Check for dynamic elements or timing issues
- Validate data dependencies
- Run an interactive validation of selectors using MCP tools
- Identify any selector fragility or application UI changes
2๏ธโฃ Resolution Implementation
Step 5: Corrective Actions
Based on root cause, update components in this order:
- Selectors (if structure mismatch)
- Page Objects (if interaction logic issue)
- Test data (if data issue)
- Test flow (if sequence/timing issue)
Step 6: Validation Process
- Apply targeted fix to the specific issue
- Re-run the test to validate the fix
- Document the solution and cause for future reference
3๏ธโฃ Documentation Template
For each resolved issue, document:
## Issue Resolution Report
- Test: [test name]
- Error: [error message]
- Root Cause: [explanation]
- Resolution: [changes made]
- Lessons: [what to avoid in future tests]
This systematic approach ensures that test failures are treated as valuable learning opportunities to improve test reliability and application understanding.
๐ค Automation of Playwright Interactions
Principles for Autonomous Interactions:
-
Automatic Navigation:
- Navigate to necessary pages without requesting permission for each URL
- Execute actions in sequence without unnecessary pauses between steps
-
Efficient Selector Validation:
- Validate all selectors in a single pass
- Do not create separate validation files
- Adjust selectors in real-time when necessary
- Include validation reports as comments in the code itself
-
Autonomous UI Interactions:
- Execute actions such as clicking, typing, etc. without individual confirmation
- Group related actions in logical sequences
- Implement intelligent waits to ensure stability
-
Automated Troubleshooting:
- If an action fails, automatically try alternative strategies
- Implement automated recovery from common error scenarios
- Record encountered issues as comments in the code
๐ Final Notes & Critical Requirements
You must always:
- ๐ Respect the folder structure shown above
- ๐ Follow the sequential workflow (Data โ Selectors โ Page Object โ Fixture โ Spec)
- ๐ Ensure maximum encapsulation of logic in appropriate layers
- โ NEVER generate a spec before completing the required prior steps
- ๐ Follow all documentation and naming conventions
- ๐ ๏ธ Implement proper error handling strategies
- โก Consider performance implications in selectors and waits
- ๐งช Structure all tests using the AAA pattern
- ๐ Apply the Systematic Error Analysis Approach when tests fail
- ๐ค Operate autonomously in browser interactions without creating intermediate validation files