Advanced Techniques
Handling Async Operations
Playwright provides robust methods for managing asynchronous behaviors:
test('handle async operations', async ({ page }) => {
// Wait for network idle
await page.waitForLoadState('networkidle');
// Wait for specific network requests
await page.waitForRequest('**/api/data');
await page.waitForResponse('**/api/data');
// Custom wait with timeout
await page.waitForFunction(() => {
return document.querySelector('#loadIndicator').textContent === 'Ready';
}, { timeout: 5000 });
});Mocking and Stubbing
Network Request Mocking
test('mock API responses', async ({ page }) => {
// Intercept and mock network requests
await page.route('**/api/users', route => {
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([
{ id: 1, name: 'Test User' }
])
});
});
// Navigate and verify mocked data
await page.goto('/users');
const userElements = await page.$$('.user-item');
expect(userElements.length).toBe(1);
});Geolocation and Permissions Mocking
Performance Testing
Page Load Performance
Advanced Interaction Techniques
Complex User Scenarios
State Management and Isolation
Accessibility Testing
Error Tracking and Screenshots
Performance Consideration Advanced techniques like mocking and extensive interactions can slow down test execution. Use judiciously and focus on critical paths.
Best Practices
Keep tests independent and isolated
Use page object models for complex interactions
Minimize hard waits, prefer dynamic waiting
Mock external dependencies
Capture meaningful metrics and errors
Last updated
Was this helpful?