PW

Playwright Cheat Sheet

BROWSER AUTOMATION & TESTING · QUICK REFERENCE GUIDE

🎓 Next Gen QA IT Coaching Classes
📞 Mr. Khan Sir  |  8700350994
CBSE/ICSE B.Tech / BCA / MCA Polytechnic Online & Offline Software Testing
Browser Management · Context · Page/Tab · Navigation · Page Info
Browser Start & Close
Launch Chromium
const { chromium } = require('playwright'); const browser = await chromium.launch();
Launch Chrome browser
const browser = await chromium.launch({ channel: 'chrome' });
Launch Microsoft Edge
const browser = await chromium.launch({ channel: 'msedge' });
Launch Firefox
const { firefox } = require('playwright'); const browser = await firefox.launch();
Launch WebKit
const { webkit } = require('playwright'); const browser = await webkit.launch();
Close browser
await browser.close();
Context Management
Create new browser context
const context = await browser.newContext();
Close browser context
await context.close();
Page / Tab Management
Open a new page / tab
const page = await context.newPage();
Wait for new tab (e.g. target=_blank)
const newPagePromise = context.waitForEvent('page'); await page.locator('a[target="_blank"]').click(); const newPage = await newPagePromise;
List all pages
const pages = context.pages();
Bring page to front
await page.bringToFront();
Close page / Check closed
await page.close(); const isClosed = page.isClosed();
Page Information
Get URL & title
const url = page.url(); const title = await page.title();
Navigation
Navigate to URL
await page.goto('https://example.com');
Reload / Back / Forward
await page.reload(); await page.goBack(); await page.goForward();
Page Assertions
Assert URL equals value
await expect(page).toHaveURL('https://example.com');
Assert URL using function
await expect(page).toHaveURL(url => { return url.pathname === '/results' && url.searchParams.get('page') === '1'; });
Assert page title
await expect(page).toHaveTitle('Dashboard');
Element Selection
CSS selector / Text / Label / Role
page.locator('#element') page.getByText('Submit') page.getByLabel('Username') page.getByRole('button', { name: 'Submit' })
Placeholder / AltText / Title / TestId
page.getByPlaceholder('Enter email') page.getByAltText('Company Logo') page.getByTitle('Close') page.getByTestId('submit-button')
Waiting for Elements · Element State · Element Assertions
Waiting for Element States
Wait: attached / visible / hidden / detached
await page.locator('#menu').waitFor({ state: 'attached' }); await page.locator('#menu').waitFor({ state: 'visible' }); await page.locator('#menu').waitFor({ state: 'hidden' }); await page.locator('#menu').waitFor({ state: 'detached' });
Wait with custom timeout (30 min)
await page.locator('#menu').waitFor({ state: 'visible', timeout: 30 * 60 * 1000 });
Element State
Get text / inner text / HTML / attribute / input value
const text = await page.locator('#el').textContent(); const text = await page.locator('#el').innerText(); const html = await page.locator('#el').innerHTML(); const href = await page.locator('#el').getAttribute('href'); const val = await page.locator('#input').inputValue();
Bounding box / isVisible / isEnabled / isChecked
const box = await page.locator('#el').boundingBox(); const isVisible = await page.locator('#el').isVisible(); const isEnabled = await page.locator('#el').isEnabled(); const isChecked = await page.locator('#cb').isChecked();
Element Assertions
Visibility / text checks
await expect(page.locator('#el')).toBeAttached(); await expect(page.locator('#el')).toBeVisible(); await expect(page.locator('#el')).toBeHidden(); await expect(page.locator('#el')).toContainText('Welcome'); await expect(page.locator('#el')).not.toContainText('Error');
Value / CSS / Attribute / Checked / Enabled
await expect(page.locator('#input')).toHaveValue('Hello'); await expect(page.locator('#el')).toHaveClass("error"); await expect(page.locator('#el')).toHaveCSS('display','block'); await expect(page.locator('#cb')).toBeChecked(); await expect(page.locator('#el')).toBeEnabled(); await expect(page.locator('#el')).toBeFocused();
Element Interactions
Click / Right-click / Double-click / Hover
await page.locator('#btn').click(); await page.locator('#btn').click({ button: 'right' }); await page.locator('#btn').dblclick(); await page.locator('#btn').hover();
Click with modifier / at position
await page.locator('#btn').click({ modifiers: ['Control'] }); await page.locator('#btn').click({ position: { x:10, y:5 } });
Drag and drop / with offset
await page.locator('#src').dragTo(page.locator('#tgt')); await page.locator('#src').dragTo(page.locator('#tgt'), { sourcePosition: { x:10, y:5 }, targetPosition: { x:10, y:5 } });
Form Input · Keyboard · Mouse · File Upload / Download · Cookies · Viewport
Form Input Interactions
Fill / Clear / Press / Type with delay
await page.locator('#input').fill('Hello World'); await page.locator('#input').clear(); await page.locator('#input').press('Enter'); await page.locator('#input').pressSequentially('Hello', { delay:100 });
Checkbox / Radio / Dropdown / Multi-select
await page.locator('#checkbox').check(); await page.locator('#checkbox').uncheck(); await page.locator('.select').selectOption('Red'); await page.locator('.select').selectOption(['Red','Green']);
Focus / Blur / Scroll into view
await page.locator('#input').focus(); await page.locator('#input').blur(); await page.locator('#el').scrollIntoViewIfNeeded();
Keyboard
Press key / chord / type text / type with delay
await page.keyboard.press('Enter'); await page.keyboard.press('Control+A'); await page.keyboard.type('Hello World'); await page.keyboard.type('Hello World', { delay: 100 });
Hold / Release key
await page.keyboard.down('Shift'); await page.keyboard.up('Shift');
Mouse
Move / Click / Right-click / Double-click / Scroll
await page.mouse.move(100, 200); await page.mouse.click(100, 200); await page.mouse.click(100, 200, { button: 'right' }); await page.mouse.dblclick(100, 200); await page.mouse.wheel(0, 100);
Press down / Release mouse button
await page.mouse.down(); // default: left button await page.mouse.up(); await page.mouse.down({ button: 'right' }); await page.mouse.up({ button: 'right' });
File Upload & Download
Upload single / multiple files
let el = page.locator('input[type="file"]'); await el.setInputFiles('photos/mountain.png'); await el.setInputFiles(['photos/mountain.png','river.png']);
Upload file from memory / Clear file input
await el.setInputFiles([{ name: 'file1.txt', mimeType: 'text/plain', buffer: Buffer.from('Hello World') }]); await el.setInputFiles([]); // clear
Download and save file
const downloadEvent = await page.waitForEvent('download'); await page.locator('#download-link').click(); const download = await downloadEvent; await download.saveAs('report.pdf');
Cookies
Get / Add / Clear all cookies
const cookies = await context.cookies(); await context.addCookies([{ name:'session-id', value:'abc123', domain:'example.com', path:'/', httpOnly:true, secure:true, sameSite:'Lax' }]); await context.clearCookies();
Clear by name / domain
await context.clearCookies({ name: 'session-id' }); await context.clearCookies({ domain: 'example.com' });
Viewport & Screenshots
Get / Set viewport size
const size = page.viewportSize(); await page.setViewportSize({ width:1280, height:720 });
Screenshot: element / viewport / full page
await page.locator('#el').screenshot({ path:'element.png' }); await page.screenshot({ path:'viewport.png' }); await page.screenshot({ path:'full.png', fullPage:true });
JavaScript Evaluate · Alert / Prompt / Confirmation Dialogs
Evaluate JavaScript
Evaluate as string / function / with arguments
const sum = await page.evaluate('1 + 2'); await page.evaluate(() => alert('Hello World')); const sum = await page.evaluate(([a, b]) => { return a + b; }, [1, 2]);
Alert / Prompt / Confirmation Dialogs
Accept / Dismiss / Enter text / Conditional
page.on('dialog', async dialog => { await dialog.accept(); // accept alert await dialog.accept('Hello World'); // prompt with text await dialog.dismiss(); // dismiss confirm if(dialog.message() === 'Are you sure?') { await dialog.accept(); } else { await dialog.dismiss(); } });