Setup & Install:
npm init playwright@latest, npx playwright install, npx playwright test.
Launch Browser:
Use chromium.launch(), firefox.launch(), or webkit.launch().
Page Navigation:
page.goto('https://example.com') — navigates to a URL.
User Actions:
Click: page.click('selector')
Fill input: page.fill('selector', 'text')
Press key: page.press('selector', 'Enter')
Element Locators:
By Text: page.locator('text=Submit')
By Role: page.getByRole('button', { name: 'Submit' })
By Test ID: page.getByTestId('id')
Assertions (using Playwright Test):
URL Check: expect(page).toHaveURL('url')
Text Check: expect(locator).toHaveText('text')
State Check: expect(locator).toBeEnabled()
Waiting:
For Element: page.waitForSelector('selector')
For Timeout: page.waitForTimeout(ms)
Multi-Tab / Context Handling:
Wait for new pages with context.waitForEvent('page').
Network Handling:
Intercept network calls using page.route('url', handler).
Authentication (Storage State):
Save session: context.storageState({ path: 'state.json' }), reuse with newContext({ storageState: 'state.json' }).
API Testing:
Use playwright.request.newContext() and make API calls like request.get(url).
Parallel Execution:
Run tests faster with npx playwright test --workers=4.
Tracing:
Enable tracing with test.use({ trace: 'on-first-retry' }), view with npx playwright show-trace trace.zip.
Screenshots and Video:
page.screenshot({ path: 'screenshot.png' }), video recording can be enabled in context options.
Page Object Model (POM):
Organize tests with classes representing pages and common functions inside them.