Skip to content

Instantly share code, notes, and snippets.

@imshaiknasir
Created January 29, 2025 07:45
Show Gist options
  • Select an option

  • Save imshaiknasir/7046dd1d7b1969772df8bdf306410b11 to your computer and use it in GitHub Desktop.

Select an option

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

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