Next we are going to detail the most common commands and methods when we are using Playwright with TypeScript. There are more, but these are the most useful.
Test Execution Commands
npx playwright test, Run all tests.
- –headed, run tests in headed mode (show browser).
- –ui, run tests in UI mode (interactive mode).
- –debug, run tests in debug mode.
- -g or –grep, run tests matching a pattern.
- –project, run tests only on specific browsers.
- –workers, specify number of parallel workers.
npx playwright test
npx playwright test --headed
npx playwright test --ui
npx playwright test --debug
npx playwright test -g "login"
npx playwright test tests/login.spec.ts
npx playwright test --project=chromium
npx playwright test --workers=1
npx playwright show-report, Open the HTML test report.
npx playwright show-report
npx playwright codegen, Open Codegen tool to record tests.
- –target, specify the language (typescript, javascript, etc.).
npx playwright codegen https://example.com
npx playwright codegen --target typescript
npx playwright test –list, List all tests without running them.
npx playwright test --list
Run specific test file or folder:
npx playwright test tests/login.spec.ts
npx playwright test tests/auth/
npx playwright test tests/login.spec.ts:10 # run test at line 10
Run tests by title:
npx playwright test -g "should login successfully"
npx playwright test --grep "login|signup"
npx playwright test --grep-invert "slow" # exclude tests matching pattern
Run tests on specific browsers:
npx playwright test --project=chromium
npx playwright test --project=firefox --project=webkit
Configuration and Setup
test, It is used to define a test case.
- .describe, to group related tests together.
- .beforeEach, to run setup code before each test.
- .afterEach, to run cleanup code after each test.
import { test, expect } from '@playwright/test';
test('basic test', async ({ page }) => {
// test code
});
test.describe('group of tests', () => {
test.beforeEach(async ({ page }) => {
await page.goto('https://example.com');
});
test('test 1', async ({ page }) => {
// test code
});
});
Navigation
goto, It is used to navigate to a URL.
- waitUntil, to wait for a specific load state (‘load’, ‘domcontentloaded’, ‘networkidle’).
await page.goto('https://example.com');
await page.goto('https://example.com', { waitUntil: 'networkidle' });
goBack / goForward, navigate through browser history.
await page.goBack();
await page.goForward();
reload, reload the current page.
await page.reload();
Locators and Selectors
locator, The main method to find elements on the page. It returns a Locator object.
const button = page.locator('button');
const byText = page.locator('text=Submit');
const byRole = page.getByRole('button', { name: 'Submit' });
const byTestId = page.getByTestId('submit-button');
const byPlaceholder = page.getByPlaceholder('Enter email');
getByRole, recommended way to locate elements by their accessible role.
await page.getByRole('button', { name: 'Sign in' }).click();
await page.getByRole('textbox', { name: 'Email' }).fill('test@example.com');
getByText, locate elements by text content.
await page.getByText('Welcome').click();
await page.getByText(/welcome/i).click(); // case insensitive
Interactions
click, Click on an element.
- button, to specify which mouse button (‘left’, ‘right’, ‘middle’).
- clickCount, for double clicks or multiple clicks.
await page.locator('button').click();
await page.locator('button').click({ button: 'right' });
await page.locator('button').click({ clickCount: 2 }); // double click
fill, Fill an input field.
await page.locator('#email').fill('test@example.com');
await page.getByLabel('Password').fill('secretpass');
type, Type text character by character with delay.
- delay, time in milliseconds between key presses.
await page.locator('#search').type('playwright', { delay: 100 });
check / uncheck, Interact with checkboxes.
await page.locator('#terms').check();
await page.locator('#newsletter').uncheck();
selectOption, Select an option from a dropdown.
await page.locator('#country').selectOption('Spain');
await page.locator('#country').selectOption({ label: 'Spain' });
await page.locator('#country').selectOption({ value: 'es' });
hover, Hover over an element.
await page.locator('.menu-item').hover();
press, Press a keyboard key.
await page.locator('#search').press('Enter');
await page.keyboard.press('Control+A');
Assertions
expect, The main assertion library from Playwright.
await expect(page.locator('h1')).toBeVisible();
await expect(page.locator('h1')).toHaveText('Welcome');
await expect(page.locator('h1')).toContainText('Welcome');
await expect(page.locator('#email')).toHaveValue('test@example.com');
await expect(page.locator('button')).toBeEnabled();
await expect(page.locator('button')).toBeDisabled();
await expect(page).toHaveURL('https://example.com/dashboard');
await expect(page).toHaveTitle(/Dashboard/);
Waits
waitForSelector, Wait for an element to appear.
- state, to wait for different states (‘attached’, ‘detached’, ‘visible’, ‘hidden’).
- timeout, maximum time to wait in milliseconds.
await page.waitForSelector('.loading', { state: 'hidden' });
await page.waitForSelector('button', { state: 'visible', timeout: 5000 });
waitForLoadState, Wait for a specific page load state.
await page.waitForLoadState('networkidle');
await page.waitForLoadState('domcontentloaded');
waitForURL, Wait for the URL to match a pattern.
await page.waitForURL('**/dashboard');
await page.waitForURL(/.*dashboard.*/);
waitForTimeout, Wait for a specific amount of time (use sparingly).
await page.waitForTimeout(1000); // wait 1 second
Page Information
textContent, Get the text content of an element.
const text = await page.locator('h1').textContent();
innerText, Get the inner text of an element.
const text = await page.locator('.description').innerText();
getAttribute, Get an attribute value from an element.
const href = await page.locator('a').getAttribute('href');
isVisible / isHidden, Check if an element is visible or hidden.
const visible = await page.locator('button').isVisible();
const hidden = await page.locator('.error').isHidden();
count, Get the number of elements matching a locator.
const itemCount = await page.locator('.item').count();
Screenshots and Videos
screenshot, Take a screenshot of the page or an element.
- path, file path to save the screenshot.
- fullPage, capture the full scrollable page.
await page.screenshot({ path: 'screenshot.png' });
await page.screenshot({ path: 'screenshot.png', fullPage: true });
await page.locator('.error').screenshot({ path: 'error.png' });
Context and Multiple Pages
newPage, Create a new page in the browser context.
const newPage = await context.newPage();
await newPage.goto('https://example.com');
pages, Get all open pages.
const pages = context.pages();
Examples
Complete login test:
test('user login', async ({ page }) => {
await page.goto('https://example.com/login');
await page.getByLabel('Email').fill('user@example.com');
await page.getByLabel('Password').fill('password123');
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page).toHaveURL('**/dashboard');
await expect(page.getByText('Welcome back')).toBeVisible();
});
Form interaction with validation:
test('form submission', async ({ page }) => {
await page.goto('https://example.com/contact');
await page.getByLabel('Name').fill('John Doe');
await page.getByLabel('Email').fill('john@example.com');
await page.getByLabel('Message').fill('This is a test message');
await page.getByLabel('Accept terms').check();
await page.getByRole('button', { name: 'Submit' }).click();
await expect(page.locator('.success-message')).toBeVisible();
await expect(page.locator('.success-message')).toHaveText('Message sent successfully');
});
Handling multiple elements:
test('check all items', async ({ page }) => {
await page.goto('https://example.com/products');
const items = page.locator('.product-item');
const count = await items.count();
for (let i = 0; i < count; i++) {
const itemText = await items.nth(i).textContent();
console.log(`Item ${i}: ${itemText}`);
}
await expect(items).toHaveCount(10);
});
Wait for element and interact:
test('wait and click', async ({ page }) => {
await page.goto('https://example.com');
// Wait for the button to be visible
await page.waitForSelector('button.submit', { state: 'visible' });
// Or use auto-waiting with locators
await page.locator('button.submit').click();
// Wait for navigation
await page.waitForURL('**/success');
await expect(page.getByText('Operation completed')).toBeVisible();
});
Working with dropdowns and selects:
test('select options', async ({ page }) => {
await page.goto('https://example.com/form');
// Select by value
await page.locator('#country').selectOption('us');
// Select by label
await page.locator('#language').selectOption({ label: 'Spanish' });
// Select multiple options
await page.locator('#interests').selectOption(['sports', 'music', 'reading']);
await expect(page.locator('#country')).toHaveValue('us');
});
Handling alerts and dialogs:
test('handle dialog', async ({ page }) => {
// Listen for dialog before it appears
page.on('dialog', async dialog => {
console.log(dialog.message());
await dialog.accept();
});
await page.goto('https://example.com');
await page.getByRole('button', { name: 'Delete' }).click();
// Dialog is automatically handled
});
