Core Concepts
Browser
A browser in Playwright refers to a web browser like Chromium, Firefox, or WebKit. Playwright allows you to automate these browsers for testing.
Launch a Browser:
You can launch a browser in headless mode (no UI) or headed mode (with UI):
const { chromium } = require('playwright'); const browser = await chromium.launch({ headless: false });
Close the Browser:
Always close the browser when you're done:
await browser.close();
Browser Context
A browser context is like a separate user session within a browser. It allows you to test different scenarios independently without interference.
Why Use Contexts?
Instead of launching multiple browsers (which is slow), you can create multiple contexts in one browser.
Creating a Context:
const context = await browser.newContext();
Benefits of Contexts:
- Each context has its own cookies and storage.
- Useful for testing scenarios like logging in as different users.
Page
A page represents a single tab or window in a browser. You'll interact with web elements on a page (like clicking buttons, typing text, etc.).
Create a New Page:
const page = await context.newPage();
Navigate to a Website:
await page.goto('https://example.com');
Multiple Pages:
You can open multiple tabs (pages) in the same context:
const page1 = await context.newPage(); const page2 = await context.newPage();
Selectors
Playwright uses selectors to identify and interact with elements on a web page.
1. Common Selectors:
css: Select elements by CSS selectors.
await page.click('button#submit');
text: Select elements by visible text.
await page.click('text=Login');
Built-In Playwright Selectors:
Playwright includes advanced selectors, such as:
- role: For accessibility testing (e.g., role=button).
- has: To find elements containing specific content.
Actions and Interactions
Playwright lets you perform actions like clicking, typing, hovering, and more.
Clicking a Button:
await page.click('button#submit');
Typing in an Input Field:
await page.fill('input#username', 'myUsername');
Hovering Over an Element:
await page.hover('.menu-item');
Automatic Waiting
Playwright automatically waits for elements to be ready before performing actions, reducing flaky tests.
Example:
await page.click('button#submit'); // Waits until the button is visible and enabled.
Emulating Devices
Playwright can simulate mobile devices to test responsive designs.
Enable Mobile Emulation:
const context = await browser.newContext({ viewport: { width: 375, height: 812 }, userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X)...', });
Built-In Device Profiles:
Use predefined device profiles:
const { devices } = require('playwright'); const iPhone = devices['iPhone 12']; const context = await browser.newContext({ ...iPhone });
Handling Frames and Pop-Ups
Playwright makes it easy to handle iframes and pop-ups.
Working with Iframes:
const frame = page.frame({ name: 'iframe-name' }); await frame.click('button#insideIframe');
Handling New Tabs/Pop-Ups:
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.click('a#openPopup'), // Action that opens the new tab ]); await newPage.goto('https://example.com');
Network Interception
You can monitor or mock network requests during tests.
Log All Requests:
page.on('request', request => { console.log('Request URL:', request.url()); });
Mock an API Response:
await page.route('https://api.example.com/data', route => route.fulfill({ status: 200, body: JSON.stringify({ success: true }), }) );
Screenshots and Videos
Playwright can capture screenshots and videos to help debug your tests.
Take a Screenshot:
await page.screenshot({ path: 'screenshot.png' });
Record a Video:
const context = await browser.newContext({ recordVideo: { dir: './videos/' } }); const page = await context.newPage();