Advanced Features
Playwright isn't just about basic automation. It comes packed with advanced features that help you test complex scenarios effectively. These features make it a powerful tool for handling modern web applications.
Handling Frames and Iframes
Sometimes, web pages have embedded content in iframes (e.g., videos or ads). Playwright makes it easy to interact with elements inside these frames.
Access an iframe:
const frame = page.frame({ name: 'frame-name' }); // Locate iframe by name or other attributes await frame.click('button#insideIframe'); // Perform actions inside the frame
List all frames on a page:
const frames = page.frames(); console.log('Frames on this page:', frames.map(frame => frame.url()));
Emulating Mobile Devices
You can test how your web app looks and works on mobile devices using Playwright’s device emulation.
Enable a mobile viewport:
const context = await browser.newContext({ viewport: { width: 375, height: 812 }, isMobile: true, userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_2 like Mac OS X)...', }); const page = await context.newPage(); await page.goto('https://example.com');
Use a built-in mobile device profile:
const { devices } = require('playwright'); const iPhone12 = devices['iPhone 12']; const context = await browser.newContext({ ...iPhone12 });
Geolocation Testing
If your app uses location-based services, you can test it with custom geolocations.
Set Geolocation:
const context = await browser.newContext({ geolocation: { latitude: 37.7749, longitude: -122.4194 }, // San Francisco permissions: ['geolocation'], // Grant geolocation permissions }); const page = await context.newPage(); await page.goto('https://example.com');
Permissions Management
Control what permissions (like camera, microphone, or notifications) a browser grants to websites.
Grant permissions:
const context = await browser.newContext({ permissions: ['camera', 'microphone'], });
Revoke permissions:
await context.clearPermissions();
Network Interception
You can intercept and modify network requests and responses to simulate different scenarios.
Monitor requests:
page.on('request', request => { console.log('Request made:', request.url()); });
Mock a response:
await page.route('https://api.example.com/data', route => route.fulfill({ status: 200, body: JSON.stringify({ success: true, data: [] }), }) );
Record and Replay User Actions
Playwright has a code generation tool to record user actions and convert them into scripts.
Start recording:
npx playwright codegen
This opens a browser where you can interact with a page. Playwright records your actions and generates code for you.
File Uploads and Downloads
Handle file uploads:
await page.setInputFiles('input[type="file"]', 'path/to/file.txt');
Download a file:
const [download] = await Promise.all([ page.waitForEvent('download'), page.click('a#downloadButton'), // Action triggering download ]); await download.saveAs('path/to/save/file.txt');
Drag-and-Drop Interactions
Simulate drag-and-drop actions for testing interactive elements.
Perform drag-and-drop:
await page.dragAndDrop('#source', '#target');
Visual Testing
Playwright can take screenshots or capture videos of your tests to help debug and track changes visually.
Take a full-page screenshot:
await page.screenshot({ path: 'fullpage.png', fullPage: true });
Record a video:
const context = await browser.newContext({ recordVideo: { dir: './videos/' }, }); const page = await context.newPage();
Parallel Testing
Run multiple tests in parallel to speed up execution.
- Use Playwright Test Runner:
- With Playwright Test Runner, parallelism is enabled by default. Each test file runs in isolation.
- Example:
- Create multiple test files (e.g., test1.spec.js, test2.spec.js) and run them using:
npx playwright test
Component Testing (Latest Feature)
Test UI components in isolation with Playwright's component testing feature. This is especially useful for React, Vue, or Angular apps.
Example setup:
npx playwright test --project=component
Trace Viewer for Debugging
Playwright captures detailed traces during test execution, which you can use to debug failures.
Enable tracing:
await context.tracing.start({ screenshots: true, snapshots: true }); await page.goto('https://example.com'); await context.tracing.stop({ path: 'trace.zip' });
View the trace:
npx playwright show-trace trace.zip