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):

Javascript
Copy
const { chromium } = require('playwright');
const browser = await chromium.launch({ headless: false });

Close the Browser:

Always close the browser when you're done:

Javascript
Copy
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:

Javascript
Copy
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:

Javascript
Copy
const page = await context.newPage();

Navigate to a Website:

Javascript
Copy
await page.goto('https://example.com');

Multiple Pages:

You can open multiple tabs (pages) in the same context:

Javascript
Copy
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.

Javascript
Copy
await page.click('button#submit');

text: Select elements by visible text.

Javascript
Copy
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:

Javascript
Copy
await page.click('button#submit');

Typing in an Input Field:

Javascript
Copy
await page.fill('input#username', 'myUsername');

Hovering Over an Element:

Javascript
Copy
await page.hover('.menu-item');

Automatic Waiting

Playwright automatically waits for elements to be ready before performing actions, reducing flaky tests.

Example:

Javascript
Copy
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:

Javascript
Copy
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:

Javascript
Copy
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:

Javascript
Copy
const frame = page.frame({ name: 'iframe-name' });
await frame.click('button#insideIframe');

Handling New Tabs/Pop-Ups:

Javascript
Copy
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:

Javascript
Copy
page.on('request', request => {
    console.log('Request URL:', request.url());
});

Mock an API Response:

Javascript
Copy
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:

Javascript
Copy
await page.screenshot({ path: 'screenshot.png' });

Record a Video:

Javascript
Copy
const context = await browser.newContext({ recordVideo: { dir: './videos/' } });
const page = await context.newPage();