CTCaliberTek
Cheat Sheets

Playwright Cheat Sheet: Locators, Assertions, Config, and CLI (TypeScript)

Published October 9, 2026·Updated October 29, 2026·8 min read
Like SaveLog in to like, save, and track progress.

Introduction

Playwright Test is a fast, reliable framework for end-to-end testing. This cheat sheet lists the locators, actions, assertions, and commands you use most. Confirm details against the official Playwright documentation for your installed version.

Prerequisites

  • Node.js installed
  • Basic TypeScript

Step-by-Step Guide

Step 1: Install and run

The initializer creates a config file, an example test, and downloads browsers.

npm init playwright@latest
npx playwright install                 # fetch browsers on a new machine

npx playwright test                    # run all tests headless
npx playwright test tests/login.spec.ts
npx playwright test --project=chromium
npx playwright test -g "login"         # by title
npx playwright test --headed           # watch the browser
npx playwright test --ui               # UI mode
npx playwright test --debug            # Inspector
npx playwright show-report
npx playwright codegen https://example.com   # record actions

Step 2: A basic test

Tests receive a page fixture. Every test gets a fresh browser context.

import { test, expect } from '@playwright/test';

test('has title', async ({ page }) => {
  await page.goto('https://playwright.dev/');
  await expect(page).toHaveTitle(/Playwright/);
});

test.describe('login', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/login');
  });
  test('shows an error for a bad password', async ({ page }) => { /* ... */ });
});

Step 3: Locators

Prefer user-facing locators. getByRole is usually best because it matches how assistive technology sees the page.

page.getByRole('button', { name: 'Sign in' });
page.getByLabel('Email');
page.getByPlaceholder('Search');
page.getByText('Welcome back');
page.getByTestId('todo-item');          // data-testid attribute
page.locator('css=.card >> text=Pricing');
page.locator('li').filter({ hasText: 'Buy milk' });
page.locator('li').nth(0);   page.locator('li').first();
row.getByRole('checkbox');              // chain to scope within a locator

Step 4: Actions

Actions wait for the element to be ready, so you rarely need manual sleeps.

await page.goto('/path');
await locator.click();
await locator.dblclick();
await locator.fill('text');             // clears then types
await locator.press('Enter');
await locator.check();    await locator.uncheck();
await locator.selectOption('blue');
await locator.hover();
await locator.setInputFiles('file.pdf');
await page.keyboard.press('Control+A');
await page.reload();     await page.goBack();

Step 5: Web-first assertions

These assertions retry until the condition is true or the timeout ends, which removes most flakiness.

await expect(locator).toBeVisible();
await expect(locator).toBeHidden();
await expect(locator).toBeEnabled();
await expect(locator).toHaveText('Saved');
await expect(locator).toContainText('Sav');
await expect(locator).toHaveValue('abc');
await expect(locator).toHaveCount(3);
await expect(locator).toHaveAttribute('href', /docs/);
await expect(page).toHaveURL(/dashboard/);
await expect(page).toHaveTitle('Home');
await expect(page).toHaveScreenshot();      // visual comparison
await expect.soft(locator).toHaveText('x'); // continue after failure

Step 6: Configuration

playwright.config.ts controls projects, retries, base URL, and tracing.

import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  fullyParallel: true,
  retries: process.env.CI ? 2 : 0,
  reporter: 'html',
  use: {
    baseURL: 'http://localhost:3000',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox',  use: { ...devices['Desktop Firefox'] } },
    { name: 'mobile',   use: { ...devices['iPhone 13'] } },
  ],
});

Step 7: API testing, mocking, and auth reuse

Use the request fixture for API calls, page.route to mock responses, and storageState to reuse a login.

test('creates an item', async ({ request }) => {
  const response = await request.post('/api/items', { data: { name: 'Pen' } });
  expect(response.ok()).toBeTruthy();
  expect((await response.json()).name).toBe('Pen');
});

await page.route('**/api/products', route =>
  route.fulfill({ status: 200, json: [{ id: 1, name: 'Mock' }] }));

await page.context().storageState({ path: 'playwright/.auth/user.json' });
// config: use: { storageState: 'playwright/.auth/user.json' }

// debugging
npx playwright show-trace trace.zip

FAQs

Why avoid fixed waits like waitForTimeout?
They slow tests and still fail on slow machines. Use auto-waiting actions and web-first assertions, which wait only as long as needed.

Summary

Use getByRole and friends for locators, rely on auto-waiting actions and web-first assertions, configure projects and traces in playwright.config.ts, and debug with UI mode, codegen, and traces.

Related tutorials

Comments

Log in or create a free account to join the discussion.

  • No comments yet. Be the first to comment.