Playwright TypeScript - Page, Locator and Other Important Classes
Playwright with TypeScript provides powerful classes and interfaces for browser automation and API testing. Understanding Page, Locator, Browser, BrowserContext, Frame, Keyboard, Mouse, and other important classes helps you build a reusable and maintainable automation framework.
1. Important Playwright Classes and Interfaces
Playwright provides several classes and interfaces to control browsers, interact with web elements, manage browser sessions, and perform API testing.
| Class or Interface | Description |
|---|---|
| Browser | Represents a browser instance such as Chromium, Firefox, or WebKit. |
| BrowserContext | Represents an isolated browser session. |
| Page | Represents a single browser tab or page. |
| Locator | Represents an element or group of elements on a page. |
| Frame | Represents an iframe inside a webpage. |
| FrameLocator | Used to locate and interact with elements inside an iframe. |
| BrowserType | Provides methods to launch browser instances. |
| APIRequestContext | Used for making API requests. |
| APIResponse | Represents an API response. |
| Request | Represents an HTTP request. |
| Response | Represents an HTTP response. |
| Download | Represents a downloaded file. |
| Dialog | Represents JavaScript dialogs such as alerts and confirms. |
| Keyboard | Provides keyboard interaction methods. |
| Mouse | Provides mouse interaction methods. |
| Touchscreen | Provides touchscreen interaction methods. |
| JSHandle | Represents a JavaScript object in the browser context. |
2. Page Class
The Page class represents a browser tab. It provides methods to navigate, interact with elements, take screenshots, and handle browser events.
Import Page
import { Page } from '@playwright/test';
Page Example
import { test, expect } from '@playwright/test';
test('Page class example', async ({ page }) => {
await page.goto('https://example.com');
const title: string = await page.title();
console.log(title);
const url: string = page.url();
console.log(url);
await page.reload();
await page.goBack();
await page.goForward();
await page.screenshot({
path: 'homepage.png'
});
await expect(page).toHaveTitle(/Example/);
});
Important Page Methods
| Method | Description |
|---|---|
| page.goto(url) | Navigate to a URL. |
| page.url() | Get current URL. |
| page.title() | Get page title. |
| page.reload() | Reload page. |
| page.goBack() | Navigate backward. |
| page.goForward() | Navigate forward. |
| page.screenshot() | Take screenshot. |
| page.locator() | Locate elements. |
| page.getByRole() | Locate by accessible role. |
| page.getByText() | Locate by text. |
| page.getByLabel() | Locate by label. |
| page.getByPlaceholder() | Locate by placeholder. |
| page.waitForLoadState() | Wait for page load state. |
| page.waitForURL() | Wait for URL change. |
| page.evaluate() | Execute JavaScript in the page. |
| page.close() | Close page. |
3. Locator Class
The Locator class is used to find and interact with HTML elements. Locators are automatically re-evaluated when used, making them suitable for dynamic web applications.
Import Locator
import { Locator } from '@playwright/test';
Locator Example
import { test, expect, Locator } from '@playwright/test';
test('Locator example', async ({ page }) => {
await page.goto('https://example.com');
const heading: Locator = page.locator('h1');
const text = await heading.textContent();
console.log(text);
await expect(heading).toBeVisible();
});
Important Locator Methods
| Method | Description |
|---|---|
| locator() | Find elements using CSS or XPath. |
| click() | Click an element. |
| dblclick() | Double-click an element. |
| fill() | Enter text into an input. |
| type() | Type text character by character. |
| press() | Press a keyboard key. |
| clear() | Clear input value. |
| check() | Check a checkbox. |
| uncheck() | Uncheck a checkbox. |
| selectOption() | Select a dropdown option. |
| hover() | Hover over an element. |
| focus() | Focus an element. |
| blur() | Remove focus. |
| textContent() | Get text content. |
| innerText() | Get visible text. |
| inputValue() | Get input value. |
| getAttribute() | Get attribute value. |
| isVisible() | Check visibility. |
| isEnabled() | Check enabled state. |
| count() | Count matching elements. |
| nth() | Select element by zero-based index. |
| first() | Select first matching element. |
| last() | Select last matching element. |
| filter() | Filter matching elements. |
| waitFor() | Wait for a locator state. |
Locator Practical Example
import { test, expect } from '@playwright/test';
test('Login form interaction', async ({ page }) => {
await page.goto('https://example.com/login');
const username = page.locator('#username');
const password = page.locator('#password');
const loginButton = page.locator('#login');
await username.fill('admin');
await password.fill('admin123');
await expect(loginButton).toBeEnabled();
await loginButton.click();
});
4. Different Ways to Create Locators
Playwright supports multiple locator strategies for identifying elements.
import { test } from '@playwright/test';
test('Different locator strategies', async ({ page }) => {
await page.goto('https://example.com');
// CSS selector
await page.locator('#username').fill('admin');
// Attribute selector
await page.locator('[id="username"]').fill('admin');
// XPath selector
await page.locator('//input[@id="username"]').fill('admin');
// Text locator
await page.getByText('Login').click();
// Role locator
await page.getByRole('button', {
name: 'Submit'
}).click();
// Label locator
await page.getByLabel('Email').fill('test@gmail.com');
// Placeholder locator
await page.getByPlaceholder('Enter username').fill('admin');
// Test ID locator
await page.getByTestId('login-button').click();
});
Best Practice: Prefer getByRole(), getByLabel(), and getByTestId() when appropriate because they generally make tests more resilient and readable.
5. Browser Class
The Browser class represents an actual browser instance.
import { test, chromium, Browser } from '@playwright/test';
test('Browser example', async () => {
const browser: Browser = await chromium.launch({
headless: false
});
const page = await browser.newPage();
await page.goto('https://example.com');
console.log(await page.title());
await browser.close();
});
Important Browser Methods
| Method | Description |
|---|---|
| browser.newPage() | Create a new page with a new context. |
| browser.newContext() | Create an isolated browser context. |
| browser.contexts() | Get existing contexts. |
| browser.isConnected() | Check browser connection. |
| browser.version() | Get browser version. |
| browser.close() | Close browser. |
6. BrowserContext Class
A BrowserContext represents an isolated browser session. Different contexts can have separate cookies, local storage, and session storage.
import {
test,
chromium,
Browser,
BrowserContext,
Page
} from '@playwright/test';
test('BrowserContext example', async () => {
const browser: Browser = await chromium.launch({
headless: false
});
const context: BrowserContext = await browser.newContext();
const page: Page = await context.newPage();
await page.goto('https://example.com');
const cookies = await context.cookies();
console.log(cookies);
await context.clearCookies();
await browser.close();
});
Important BrowserContext Methods
| Method | Description |
|---|---|
| newPage() | Create a page. |
| pages() | Get all pages. |
| cookies() | Get cookies. |
| addCookies() | Add cookies. |
| clearCookies() | Clear cookies. |
| storageState() | Get authentication storage state. |
| grantPermissions() | Grant browser permissions. |
| clearPermissions() | Clear browser permissions. |
| close() | Close context. |
7. Frame and FrameLocator
Frames are used when a webpage contains an iframe.
Example HTML
<iframe id="payment-frame"></iframe>
Using FrameLocator
import { test } from '@playwright/test';
test('Iframe example', async ({ page }) => {
await page.goto('https://example.com');
const paymentFrame = page.frameLocator(
'#payment-frame'
);
await paymentFrame
.locator('#card-number')
.fill('123456789');
await paymentFrame
.getByRole('button', { name: 'Pay' })
.click();
});
Frame vs FrameLocator
| Frame | FrameLocator |
|---|---|
| Represents an actual iframe frame. | Provides a locator for an iframe. |
| Can access frame URL and evaluate JavaScript. | Locates elements inside an iframe. |
| Obtained using page.frame(). | Obtained using page.frameLocator(). |
| Useful for frame-level operations. | Useful for UI automation. |
8. Keyboard Class
The Keyboard class provides keyboard interaction methods.
import { test } from '@playwright/test';
test('Keyboard example', async ({ page }) => {
await page.goto('https://example.com');
await page.locator('#username').focus();
await page.keyboard.type('admin');
await page.keyboard.press('Tab');
await page.keyboard.type('admin123');
await page.keyboard.press('Enter');
});
Common Keyboard Methods
- keyboard.press()
- keyboard.type()
- keyboard.insertText()
- keyboard.down()
- keyboard.up()
9. Mouse Class
The Mouse class is used for mouse interactions.
import { test } from '@playwright/test';
test('Mouse example', async ({ page }) => {
await page.goto('https://example.com');
await page.mouse.move(100, 200);
await page.mouse.click(100, 200);
await page.mouse.dblclick(100, 200);
await page.mouse.wheel(0, 500);
});
Common Mouse Methods
- mouse.click()
- mouse.dblclick()
- mouse.move()
- mouse.down()
- mouse.up()
- mouse.wheel()
10. APIRequestContext Class
APIRequestContext is used for API testing without opening a browser UI. Playwright supports HTTP methods such as GET, POST, PUT, PATCH, and DELETE.
import {
test,
expect,
APIRequestContext
} from '@playwright/test';
test('API request example', async ({ request }) => {
const apiRequest: APIRequestContext = request;
const response = await apiRequest.get(
'https://petstore.swagger.io/v2/pet/1'
);
expect(response.status()).toBe(200);
const responseBody = await response.json();
console.log(responseBody);
});
Important APIRequestContext Methods
| Method | Description |
|---|---|
| get() | Send GET request. |
| post() | Send POST request. |
| put() | Send PUT request. |
| patch() | Send PATCH request. |
| delete() | Send DELETE request. |
| fetch() | Send a custom HTTP request. |
| dispose() | Dispose request context. |
11. How Playwright Classes Work Together
The following structure explains the relationship between Browser, BrowserContext, Page, and Locator.
Browser
|
+-- BrowserContext
|
+-- Page 1
| |
| +-- Locator
|
+-- Page 2
|
+-- Locator
- Browser: Launches Chromium, Firefox, or WebKit.
- BrowserContext: Creates an isolated browser session.
- Page: Opens a browser tab.
- Locator: Identifies an HTML element.
- Keyboard: Performs keyboard interactions.
- Mouse: Performs mouse interactions.
12. TypeScript Imports Cheat Sheet
| Class or Function | Import Statement |
|---|---|
| Page | import { Page } from '@playwright/test' |
| Locator | import { Locator } from '@playwright/test' |
| Browser | import { Browser } from '@playwright/test' |
| BrowserContext | import { BrowserContext } from '@playwright/test' |
| Frame | import { Frame } from '@playwright/test' |
| FrameLocator | import { FrameLocator } from '@playwright/test' |
| APIRequestContext | import { APIRequestContext } from '@playwright/test' |
| APIResponse | import { APIResponse } from '@playwright/test' |
| Request | import { Request } from '@playwright/test' |
| Response | import { Response } from '@playwright/test' |
| Download | import { Download } from '@playwright/test' |
| Dialog | import { Dialog } from '@playwright/test' |
| Keyboard | import { Keyboard } from '@playwright/test' |
| Mouse | import { Mouse } from '@playwright/test' |
Important: These types can be imported from @playwright/test. You generally do not need to create browser objects manually in every test because Playwright Test provides fixtures such as page, context, and browser.
13. Practical Exercise
Try creating a login page automation framework using the following classes:
- Browser: Launch Chromium.
- BrowserContext: Create a browser session.
- Page: Open the login page.
- Locator: Identify username and password fields.
- Keyboard: Enter login details.
- Mouse: Perform mouse interactions.
- FrameLocator: Handle iframe-based login.
- Expect: Validate login results.

No comments:
Post a Comment