Test structure
Playwright tests are written using thetest function from @playwright/test. Each test receives a page object for browser interaction.
Locators: Finding elements
Playwright uses locators to find elements on the page. Locators are auto-waiting and retry-able, making tests more reliable.Recommended locators
- By role
- By text
- By test ID
- By label
The most resilient way to locate elements (recommended):
Chaining and filtering locators
Combine locators to narrow down your selection:Web-first assertions
Playwright assertions automatically retry until the condition is met or timeout is reached.Common assertions
Custom timeout for assertions
Real-world test examples
Example 1: Form submission
Complete form interaction from the TodoMVC example:Example 2: Editing with double-click
Example 3: API testing
Test REST APIs directly from the GitHub API example:Example 4: Mocking browser APIs
Mock the Battery API from the mock-battery example:Organizing tests
Test groups
Organize related tests withtest.describe():
Test hooks
Set up and tear down test state:Custom fixtures
Extend test context with reusable setup:Configuration
Configure test behavior inplaywright.config.ts:
Best practices
Use web-first assertions
Use web-first assertions
Always use Playwright’s
expect() assertions instead of regular assertions. They automatically retry and wait for conditions to be met.Avoid manual waits
Avoid manual waits
Don’t use
setTimeout() or page.waitForTimeout(). Playwright’s auto-waiting handles timing automatically.Use meaningful test descriptions
Use meaningful test descriptions
Test names should clearly describe what they verify:
Keep tests independent
Keep tests independent
Each test should be able to run in isolation. Don’t rely on the order of test execution.
Use test fixtures for common setup
Use test fixtures for common setup
Extract repeated setup code into custom fixtures to keep tests DRY:
Next steps
Locators
Deep dive into locator strategies
Assertions
Master web-first assertions
Configuration
Configure advanced test options
Best practices
Learn testing best practices
Auto-waiting behavior
Playwright automatically waits for elements to be:
- Attached to the DOM
- Visible on the page
- Stable (not animating)
- Enabled and not disabled
- Not covered by other elements
