0% found this document useful (0 votes)
22 views18 pages

Playwright Command Reference Guide

Uploaded by

sneharaju
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views18 pages

Playwright Command Reference Guide

Uploaded by

sneharaju
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Playwright Cheatsheet

A quick reference guide to commonly used Playwright commands for browser automation
and testing.

Browser Start and Close


StartSearch...
 a Chromium browser instance JavaScript Python (Sync) Python (Async)

const { chromium } = require('playwright');

const browser = await [Link]();

Start a Chrome browser instance

const { chromium } = require('playwright');

const browser = await [Link]({ channel: 'chrome' });

Start a Microsoft Edge browser instance

const { chromium } = require('playwright');


const browser = await [Link]({ channel: 'msedge' });
Start a Firefox browser instance

const { firefox } = require('playwright');

const browser = await [Link]();

Start a WebKit browser instance

const { webkit } = require('playwright');


const browser = await [Link]();

Close the browser instance

await [Link]();

Context Management
Create a new browser context

const context = await [Link]();

Close the browser context

await [Link]();

Page / Tab Management


Open a new page / tab

const page = await [Link]();

Wait for a new page / tab to be opened (e.g. from clicking a link with target="_blank")

// add wait before the action that opens the new page
const newPagePromise = [Link]('page');

// perform the action that opens the new page,


// e.g. clicking a link
await [Link]('a[target="_blank"]').click();

// wait for the new page to be opened


const newPage = await newPagePromise;

List all pages

const pages = [Link]();

Make the page / tab the active one

await [Link]();

Close the current page / tab

await [Link]();

Check if the page / tab is closed

const isClosed = [Link]();

Page Information
Get the current page URL

const url = [Link]();

Get the current page title

const title = await [Link]();

Page Assertions
Requires import { expect } from '@playwright/test'
Assert the url of a page equals a specific value

await expect(page).toHaveURL('[Link]

Assert the url of a page using a function

await expect(page).toHaveURL(url => {


return [Link] === '/results'
&& [Link]('page') === '1';
});

Assert the title of a page equals a specific value

await expect(page).toHaveTitle('Dashboard');

Navigation
Navigate to a URL

await [Link]('[Link]

Reload the current page

await [Link]();

Navigate back in history

await [Link]();

Navigate forward in history

await [Link]();

Element Selection
Select an element using a CSS selector

const element = [Link]('#element');

Select an element containing specific text

const element = [Link]('Submit');

Select a form element by its associated label text

const element = [Link]('Username');

Select an element by its ARIA role and name

const element = [Link]('button', { name: 'Submit' });

Select an input element by its placeholder text

const element = [Link]('Enter your email');

Select an image element by its alt text

const element = [Link]('Company Logo');

Select an element by its title attribute

const element = [Link]('Close');

Select an element by its data-testid attribute

const element = [Link]('submit-button');

Waiting for Element States


Wait for an element to be present in the DOM
await [Link]('#menu').waitFor({ state: 'attached' });

Wait for an element to be visible on the page

await [Link]('#menu').waitFor({ state: 'visible' });

Wait for an element to be visible on the page with a custom timeout

await [Link]('#menu').waitFor({
state: 'visible',
timeout: 30 * 60 * 1000 // 30 minutes
});

Wait for an element to be hidden or removed from the page

await [Link]('#menu').waitFor({ state: 'hidden' });

Wait for an element to be removed from the DOM

await [Link]('#menu').waitFor({ state: 'detached' });

Element State
Get the text content of an element

const text = await [Link]('#element').textContent();

Get the inner text of an element

const text = await [Link]('#element').innerText();

Get the inner HTML of an element

const html = await [Link]('#element').innerHTML();


Get the outer HTML of an element

const html = await [Link]('#element').outerHTML();

Get the value of a specific attribute of an element

const href = await [Link]('#element').getAttribute('href');

Get the value of an input element

const value = await [Link]('#input').inputValue();

Get the bounding box of an element

// box contains x, y, width, height


const box = await [Link]('#element').boundingBox();

Check if an element is visible on the page

const isVisible = await [Link]('#element').isVisible();

Check if an element is hidden on the page

const isHidden = await [Link]('#element').isHidden();

Check if an element is enabled

const isEnabled = await [Link]('#element').isEnabled();

Check if an element is disabled

const isDisabled = await [Link]('#element').isDisabled();

Check if a checkbox or radio button is checked

const isChecked = await [Link]('#checkbox').isChecked();


Check if an element is editable

const isEditable = await [Link]('#input').isEditable();

Element Assertions
Requires import { expect } from '@playwright/test'

Assert that an element is attached to the DOM

await expect([Link]('#element')).toBeAttached();

Assert that an element is visible on the page

await expect([Link]('#element')).toBeVisible();

Assert that an element is hidden on the page

await expect([Link]('#element')).toBeHidden();

Assert that an element contains specific text (case insensitive)

await expect([Link]('#element')).toContainText('Welcome Master Bruce');

Assert that an element contains specific text (case insensitive)

await expect([Link]('#element')).toContainText(
'wElComE mAster bRuCe',
{ ignoreCase: true }
);

Assert that an element does not contain specific text

await expect([Link]('#element')).[Link]('Error');

Assert that an input element has a specific value


await expect([Link]('#input')).toHaveValue('Hello World');

Assert that a multi-select element has specific selected values

await expect([Link]('#multi-select')).toHaveValues([
'red', 'green'
]);

Assert that an element contains a specific CSS class

await expect([Link]('#element')).toHaveClass("error");

Assert that an element does not contain a specific CSS class

await expect([Link]('#element')).[Link]("error");

Assert that an element has a specific CSS style

await expect([Link]('#element')).toHaveCSS(
'display', 'block'
);

Assert that an element has a specific attribute with a specific value

await expect([Link]('#element')).toHaveAttribute('alt-text');

Assert that an element has a specific attribute with a specific value

await expect([Link]('#element')).toHaveAttribute(
'alt-text', 'Company Logo'
);

Assert that a checkbox or radio button is checked

await expect([Link]('#checkbox')).toBeChecked();

Assert that a checkbox or radio button is not checked


await expect([Link]('#checkbox')).[Link]();

Assert that an element is enabled

await expect([Link]('#element')).toBeEnabled();

Assert that an element is disabled

await expect([Link]('#element')).toBeDisabled();

Assert that an element is focused

await expect([Link]('#element')).toBeFocused();

Element Click / Hover / Drag and Drop


Click on an element

await [Link]('#button').click();

Right click on an element

await [Link]('#button').click({ button: 'right' });

Double click on an element

await [Link]('#button').dblclick();

Click on an element with keyboard modifiers (e.g. Ctrl, Shift)

await [Link]('#button').click({ modifiers: ['Control'] });

Click on an element at specific coordinates

await [Link]('#button').click({ position: { x: 10, y: 5 } });


Hover over an element

await [Link]('#button').hover();

Hover over an element at specific coordinates relative to top-left of the element

await [Link]('#button').hover({ position: { x: 10, y: 5 } });

Drag an element and drop it onto another element

await [Link]('#source').dragTo([Link]('#target'));

Drag an element and drop it onto another element with an offset

await [Link]('#source').dragTo([Link]('#target'), {
// relative to the top-left of the source element
sourcePosition: { x: 10, y: 5 }
// relative to the top-left of the target element
targetPosition: { x: 10, y: 5 }
});

Mouse
Move the mouse to specific coordinates relative to viewport

await [Link](100, 200);

Click the mouse at the current position

await [Link]();
await [Link]();

Click the mouse at specific coordinates relative to viewport

await [Link](100, 200);


Click the mouse with a specific button (e.g. right button) at specific coordinates relative to viewport

await [Link](100, 200, { button: 'right' });

Double-click the mouse at specific coordinates relative to viewport

await [Link](100, 200);

Press the mouse button down

await [Link]();

Press the mouse button down with options

await [Link]({ button: 'right'});

Release the mouse button

await [Link]();

Release the mouse button with options

await [Link]({ button: 'right'});

Scroll the mouse wheel by deltaX and deltaY

await [Link](0, 100);

Form Input Element Interactions


Fill a text input

await [Link]('#input').fill('Hello World');

Use press to type text input


await [Link]('#input').press('Enter');

Use press to send a key chord (e.g. Control+A to select all text)

await [Link]('#input').press('Control+A');

Use pressSequentially to type text input with a delay between each key

await [Link]('#input').pressSequentially(
'Hello',
{ delay: 100 }
);

Clear a text input

await [Link]('#input').clear();

Check a checkbox

await [Link]('#checkbox').check();

Uncheck a checkbox

await [Link]('#checkbox').uncheck();

Select an option in a dropdown by label or value

await [Link]('.select-color').selectOption('Red');

Select multiple options in a multi-select dropdown

await [Link]('.select-color').selectOption([
'Red', 'Green'
]);

Keyboard
Press a key

await [Link]('Enter');

Press a key chord (e.g. Control+A to select all text)

await [Link]('Control+A');

Type text with delay between each key

await [Link]('Hello World');

Type text with delay between each key

await [Link]('Hello World', { delay: 100 });

Hold a key down (without releasing it)

await [Link]('Shift');

Release a key that is being held down

await [Link]('Shift');

Element Interactions
Focus an element

await [Link]('#input').focus();

Remove focus from an element

await [Link]('#input').blur();

Scroll an element into view if it is not already visible


await [Link]('#element').scrollIntoViewIfNeeded();

Focuses on an element and selects all its text content

await [Link]('#element').selectText();

File Upload and Download


Upload a single file to a file input element

let el = [Link]('input[type="file"]');
await [Link]('photos/[Link]');

Upload multiple files to a file input element

let el = [Link]('input[type="file"]');
await [Link]([
'photos/[Link]',
'photos/[Link]'
]);

Upload multiple files from memory to a file input element

let el = [Link]('input[type="file"]');
await [Link]([
{
name: '[Link]',
mimeType: 'text/plain',
buffer: [Link]('Hello World')
}
]);

Clear a file input element

let el = [Link]('input[type="file"]');
await [Link]([]);

Download a file and save it to disk


// set up a download listener before clicking
const downloadEvent = await [Link]('download');

// trigger download
await [Link]('#download-link').click();

// wait for the download to complete


const download = await downloadEvent;
await [Link]('[Link]');

Evaluate javascript
Evaluate JavaScript in the page context as a string

const sum = await [Link]('1 + 2');

Evaluate JavaScript in the page context as a function

await [Link](() => alert('Hello World'));

Evaluate JavaScript in the page context with arguments

const sum = await [Link](([a, b]) => {


return a + b;
}, [1, 2]);

Alert / Prompt / Confirmation Dialogs


Listen for an alert dialog and accept it

[Link]('dialog', async dialog => {


await [Link]();
});

Listen for a prompt dialog and enter text before accepting it

[Link]('dialog', async dialog => {


await [Link]('Hello World');
});
Listen for a confirmation dialog and dismiss it

[Link]('dialog', async dialog => {


await [Link]();
});

Listen for an alert dialog and get its message

[Link]('dialog', async dialog => {


if([Link]() === 'Are you sure?') {
await [Link]();
} else {
await [Link]();
}
});

Cookies
Get all cookies for the current context

const cookies = await [Link]();

Add cookies to the current context

await [Link]([{
name: 'session-id',
value: 'abc123',
domain: '[Link]',
path: '/',
expires: 24 * 60 * 60, // 1 day from now
httpOnly: true,
secure: true,
sameSite: 'Lax'
}]);

Clear all cookies in the current context

await [Link]();

Clear a cookie with a specific name


await [Link]({ name: 'session-id' });

Clear cookies for a specific domain

await [Link]({ domain: '[Link]' });

Viewport / Window Size


Get the current viewport size

// returns { width: number, height: number }


const viewportSize = [Link]();

Set the viewport size

await [Link]({ width: 1280, height: 720 });

Screenshots
Take a screenshot of a specific element

const element = [Link]('#element');


await [Link]({ path: '[Link]' });

Take a screenshot of the current viewport

await [Link]({ path: '[Link]' });

Take a screenshot of the entire page

await [Link]({ path: '[Link]', fullPage: true });

You might also like