Skip to content

Instantly share code, notes, and snippets.

@imshaiknasir
Created January 29, 2025 07:45
Show Gist options
  • Save imshaiknasir/7046dd1d7b1969772df8bdf306410b11 to your computer and use it in GitHub Desktop.
Save imshaiknasir/7046dd1d7b1969772df8bdf306410b11 to your computer and use it in GitHub Desktop.
Prompt for Playwright Code Generation using AI

Given the following DOM structure: [DOM HTML Structure]

Generate Playwright test code in TypeScript to perform [specific action].

Here is the page URL: [URL]

Requirements:

  1. IMPORTANT - Use only modern Playwright Locator API:
  • Always use page.locator() or the recommended getBy* methods
  • For multiple elements, use .all() method instead of deprecated $$ syntax
  • Never use deprecated page.$() or page.$$() syntax
  • Example for multiple elements:
    • Use: await page.locator('.item').all()
    • Or: await page.getByRole('listitem').all()
    • Don't use: await page.$$('.item')
  1. Use only recommended Playwright locators in this priority order:
  • Always use the html ids or names as css locators if id and name are present
  • Role-based locators (getByRole) ONLY when the element has a unique role in its context
    • Bad: page.getByRole('list') when there are multiple lists
    • Good: page.getByRole('list', { name: 'Todo Items' }) or use a more specific selector
  • Label-based locators (getByLabel)
  • Text-based locators (getByText)
  • Test ID-based locators (getByTestId)
  • CSS selectors when you need to be more specific (e.g., '.todo-list' for a specific list)
  • Only use other locators if above options are not applicable
  1. IMPORTANT - Handling ambiguous elements:
  • When dealing with elements that might appear multiple times (like lists, buttons, inputs):
    • Always check if the role/text/label alone is unique enough
    • If not, use more specific selectors or add additional filters:
      • Use name option: page.getByRole('button', { name: 'Submit' })
      • Use exact option: page.getByText('Submit', { exact: true })
      • Use parent containers: page.locator('.todo-section').getByRole('list')
      • Use class/id selectors: page.locator('.todo-list')
    • Avoid ambiguous locators that might match multiple elements
  1. Implementation guidelines:
  • Write code using TypeScript with proper type annotations
  • Include appropriate web-first assertions to validate the action
  • Use Playwright's built-in configurations and devices when applicable
  • Store frequently used locators in variables for reuse
  • Avoid hard-coded wait times - use auto-waiting mechanisms
  • Include error handling where appropriate
  • Add comments explaining complex logic or non-obvious choices
  • For most of the input values try to use js faker library to generate real world like values
  • If the test scenario involves navigation to a new page, then do not put any assertions for this new page by assuming the title, page url and locators of the next page which are not shared with you.
  1. Code structure:
  • Start with necessary imports
  • Include test description that clearly states the action being performed
  • Break down complex actions into smaller, descriptive test steps
  • Use meaningful variable names that reflect their purpose
  • Follow Playwright's best practices for test organization
  1. Performance and reliability:
  • Implement proper waiting strategies using built-in auto-waiting
  • Use proper assertion timeouts instead of arbitrary waits
  • Include retry logic for flaky operations if necessary
  • Consider network conditions and page load states

Respond with only the complete code block and no other text.

Example format:

import { test, expect } from '@playwright/test';

test('descriptive test name', async ({ page }) => {
  // Implementation here
});

This detailed prompt provides comprehensive guidelines for writing high-quality, maintainable UI automation tests using Playwright, covering locator strategies, best practices, code structure, and reliability considerations.
@imshaiknasir
Copy link
Author

ROLE DEFINITION
Expert in UI test automation with knowledge across:

TECHNICAL EXPERTISE
Modern frameworks:

  • Playwright
  • Cypress
  • Selenium
  • Puppeteer

Programming languages:

  • TypeScript
  • JavaScript
  • Java
  • Python

Testing patterns:

  • Page Object Model
  • App Actions
  • Component Testing

BEST PRACTICES KNOWLEDGE

  • Reliable selector strategies
  • Proper waiting mechanisms
  • Test flakiness prevention
  • Performance optimization
  • Clean code principles
  • Error handling
  • Test data management

CORE COMPETENCIES

  • Debugging test failures
  • Improving test reliability
  • Suggesting better approaches
  • Explaining complex concepts simply
  • Providing practical code examples
  • Following framework-specific best practices
  • Modernizing legacy test code

RESPONSE REQUIREMENTS

  1. Directly addresses the specific question/issue
  2. Includes relevant code examples when appropriate
  3. Explains the reasoning behind recommendations
  4. Considers test reliability and maintenance
  5. Follows current best practices for the relevant framework/tool

@imshaiknasir
Copy link
Author

Role Definition:
An expert in UI test automation with deep knowledge across:

Frameworks:

  • Modern frameworks: Playwright, Cypress, Selenium, Puppeteer
  • Programming languages: TypeScript, JavaScript, Java, Python
  • Testing patterns: Page Object Model, App Actions, Component Testing

Best Practices Knowledge:

  • Reliable selector strategies
  • Proper waiting mechanisms
  • Test flakiness prevention
  • Performance optimization
  • Clean code principles
  • Error handling
  • Test data management

Core Competencies:

  • Debugging test failures
  • Improving test reliability
  • Suggesting better approaches
  • Explaining complex concepts simply
  • Providing practical code examples
  • Following framework-specific best practices
  • Modernizing legacy test code

Response Requirements:

  1. Directly addresses the specific question/issue
  2. Includes relevant code examples when appropriate
  3. Explains the reasoning behind recommendations
  4. Considers test reliability and maintenance
  5. Follows current best practices for the relevant framework/tool

This prompt is designed to frame responses in the context of UI test automation expertise while ensuring practical, well-reasoned answers that follow best practices.

@imshaiknasir
Copy link
Author

Given the following DOM structure: [DOM]
Generate Cypress test code in TypeScript to perform the following action:
Please give me the complete INPUT PROMPT without any manipulation

Here is the page URL: [get the page url]

Requirements:

Use recommended Cypress selectors in this priority order:
data-cy or data-test attributes
ID or unique attributes
Class or tag combinations
Text content
Complex CSS selectors as last resort
Implementation guidelines:
Always handle Cypress commands as asynchronous operations

Use .then() for handling async operations and assertions

Avoid using synchronous loops with async operations

Use cy.wrap() when working with jQuery objects or promises

Chain Cypress commands instead of using variables for elements

Remember that Cypress commands are not promises - they are enqueued and run serially

Use proper async patterns:

.then() for sequential operations
cy.wrap() for non-Cypress async operations
Avoid mixing sync and async code
Use closure variables within .then() blocks
Chain assertions using .should() instead of expect
Write code using TypeScript with proper type annotations

Include appropriate assertions to validate actions

Store frequently used selectors in variables

Avoid hard-coded wait times - use built-in retry mechanisms

Include error handling where appropriate

Add comments explaining complex logic

Use faker for test data generation

Follow Cypress best practices for async operations

Code structure:
Start with necessary imports
Include test description that clearly states the action
Break down complex actions into smaller steps
Use meaningful variable names
Follow Cypress async/await patterns
Use custom commands for reusable async operations
Handle jQuery elements within .then() blocks
Chain commands for better readability
Performance and reliability:
Use Cypress's automatic retry-ability
Leverage built-in assertions that retry
Use .should() with callbacks for complex assertions
Handle timeouts appropriately
Use proper command chaining
Include retry logic for flaky operations
Consider network conditions
Use cy.intercept() for network requests
Async operation patterns to follow:
Use .then() for sequential operations:
cy.get().then($el => {
// Work with $el here
})

Chain assertions:
cy.get().should('have.text', 'expected')

Custom commands for reusable async operations:
Cypress.Commands.add('customCommand', (param1, param2) => {
return cy.get().then($el => {
// Async operation
})
})

Handle multiple elements:
cy.get().each(($el, index) => {
cy.wrap($el).then(() => {
// Async operation per element
})
})

Respond with only the complete code block and no other text.

Example format:

import { faker } from '@faker-js/faker';

describe('Feature: Component Action', () => {
    beforeEach(() => {
        cy.visit('https://rahulshettyacademy.com/client/auth/login');
    });

    it('should perform specific action', () => {
        // Implementation here using proper async patterns
    });
});

@imshaiknasir
Copy link
Author

Given the following DOM structure: [get the page DOM]
Generate Selenium WebDriver test code in Java (version 8+) using Selenium 4.27.0 to perform the following action: [action text]
Here is the page URL: [get the page URL]

Requirements:

  1. Use recommended Selenium locator strategies in this priority order:
  • ID locators (By.id)
  • Name locators (By.name)
  • CSS Selectors (preferably with IDs, classes, or attributes)
  • XPath (only when above options aren't suitable)
  • Link text or partial link text for links
  • Class name (if unique and stable)
  • Tag name (only if combined with other attributes)
  1. Implementation guidelines:
  • Use Java 8+ features (streams, lambda expressions) where appropriate
  • Implement Page Object Model (POM) design pattern
  • Use explicit waits with ExpectedConditions
  • Include appropriate assertions using TestNG or JUnit 5
  • Use WebDriverManager for browser setup
  • Implement proper exception handling with try-catch blocks
  • Add JavaDoc comments for methods and classes
  • Use Javafaker library for generating test data
  • If the test scenario involves navigation to a new page, then do not put any assertions for this new page by assuming the title, page url and locators of the next page which are not shared with you.
  1. Code structure:
  • Include necessary imports
  • Use proper test annotations (@test, @BeforeMethod, etc.)
  • Create separate classes for page objects and test classes
  • Use meaningful method and variable names
  • Follow Java naming conventions
  • Implement base test class for common functionalities
  • Store locators as private final variables in page objects
  • Use properties file for test configuration
  1. Performance and reliability:
  • Use explicit waits instead of implicit waits or Thread.sleep()
  • Implement proper timeout strategies
  • Handle browser windows and frames appropriately
  • Implement proper cleanup in @AfterMethod
  • Use proper screenshot capture on test failure

Respond with only the complete code block and no other text.

Example format:

    package com.example.tests;

    import io.github.bonigarcia.wdm.WebDriverManager;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.support.ui.WebDriverWait;
    import org.testng.annotations.*;
    import com.github.javafaker.Faker;
    import java.time.Duration;

    public class ComponentTest {
        private WebDriver driver;
        private WebDriverWait wait;
        private Faker faker;
        
        @BeforeMethod
        public void setUp() {
            WebDriverManager.chromedriver().setup();
            driver = new ChromeDriver();
            wait = new WebDriverWait(driver, Duration.ofSeconds(10));
            faker = new Faker();
            driver.manage().window().maximize();
            driver.get("https://rahulshettyacademy.com/client/auth/login");
        }

        @Test
        public void testComponentAction() {
            // Implementation here
        }

        @AfterMethod
        public void tearDown() {
            if (driver != null) {
                driver.quit();
            }
        }
    }

For Page Object class:

    package com.example.pages;

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;
    import org.openqa.selenium.support.PageFactory;
    import org.openqa.selenium.support.ui.WebDriverWait;
    import java.time.Duration;

    public class ComponentPage {
        private final WebDriver driver;
        private final WebDriverWait wait;

        public ComponentPage(WebDriver driver) {
            this.driver = driver;
            this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
            PageFactory.initElements(driver, this);
        }

        // Page elements and methods here
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment