9. Network Interception
Block Resources Syntax
await page.route('**/*.{png,jpg,css}', route => route.abort());
Ø
page.route(): Intercept network requests
Ø
**/*.{png,jpg,css}: Pattern to match URLs
ending with these extensions
Ø
route.abort(): Blocks the request from
proceeding
Mock API Response Example
await page.route('**/api/user', async route => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ name: 'Mock
User' }),
});
});
Ø
route.fulfill(): Sends a custom response
Ø
Useful for testing edge cases without real API
dependencies
10. Handling Frames
Frame Access Syntax
const frame = page.frame({ name: 'login-frame' });
Ø
page.frame(): Finds frame by name/URL
Ø
Frames are separate HTML documents embedded in the
page
11. File Operations
Upload Syntax
await page.setInputFiles('input[type="file"]', 'path/to/file.txt');
Ø
setInputFiles(): Simulates file selection
dialog
Ø
Can handle multiple files: ['file1.txt',
'file2.txt']
12. Multiple Tabs
Popup Handling Example
const [popup] = await Promise.all([
page.waitForEvent('popup'),
page.click('a[target="_blank"]'),
]);
Ø
waitForEvent(): Listens for new browser
tab/window
Ø
Promise.all: Handles concurrent actions
13. Test Runner
Test Structure
test('Login Test', async ({ page }) => {
// Test steps
});
Ø
test: Defines a test case
Ø
expect: Assertion library for
validations
14. Assertions
Element Visibility Check
await expect(page.locator('.status')).toBeVisible();
Ø
Auto-waits for element to appear
Ø
Other assertions: toBeChecked(), toHaveValue()
15. Cookies
Cookie Setup
await context.addCookies([{
name: 'session',
value: '123',
url: 'https://example.com',
}]);
Ø
Cookies are set at context level
Ø
Persist across pages in same context
16. Device Emulation
Mobile Setup
const context = await browser.newContext({
...devices['iPhone 13'],
locale: 'en-US'
});
Ø
devices: Pre-configured mobile
profiles
Ø
Emulates screen size, user agent, touch support
17. Advanced Context
Proxy Configuration
const browser = await chromium.launch({
proxy: { server: 'http://myproxy:3128'
}
});
Ø
Routes all browser traffic through proxy
Ø
Can add authentication: username: 'user',
password: 'pass'
18. Best Practices
Page Object Model Example
// login-page.js
export class LoginPage {
constructor(page) {
this.page = page;
this.username = page.locator('#username');
}
async login(user) {
await this.username.fill(user);
}
}
Key Javascript Concepts
1. Async/Await: Used for all Playwright
operations
async function test() {
await page.click();
}
2. Destructuring:
const { test, expect } = require('@playwright/test');
3. Arrow Functions:
page.route('**/*', (route) => route.continue());
0 Comments