Playwright tests follow a consistent, easy-to-understand structure:
const { test, expect } = require('@playwright/test');
test('description of test scenario', async ({ page }) => {
// Test implementation
});
// Group related tests
test.describe('Feature Group', () => {
test('specific test case', async ({ page }) => {
// Test implementation
});
});
Locating Elements
Playwright provides multiple strategies for element selection:
// By CSS Selector
await page.locator('.login-button');
// By Text
await page.getByText('Submit');
// By Role
await page.getByRole('button', { name: 'Login' });
// By Test ID (Recommended for stability)
await page.getByTestId('login-submit');
Best Practices for Element Locators
Prefer data-testid attributes for most reliable selection
Avoid using complex CSS selectors or brittle locators
Interactions
Common user interactions:
// Clicking
await page.click('.submit-button');
// Typing
await page.fill('#username', 'testuser');
// Handling dropdowns
await page.selectOption('select#role', 'admin');
// Checkbox and radio buttons
await page.check('#agree-terms');
// Hover and complex interactions
await page.hover('.dropdown-menu');