E2E Testing TypeScript Apps with Playwright: Full Guide
Playwright is the best tool for end-to-end testing TypeScript applications. It has first-class TypeScript support, a powerful fixture system for typed test context, built-in waiting, and parallel test execution. This guide covers setting up Playwright in a TypeScript project, writing Page Object Models with proper types, handling authentication, running visual regression tests, and wiring everything into CI.
Key Takeaways
Use test.extend to create typed fixtures. Playwright fixtures replace beforeEach/afterAll blocks with typed, composable test context. A loggedInPage fixture is cleaner than duplicating auth steps.
Page Object Models prevent selector duplication. Every selector string lives in one class. When the UI changes, you update one file — not 50 tests.
waitForURL and waitForSelector beat page.waitForTimeout. Never use arbitrary sleeps. Playwright's auto-waiting handles most cases; for the rest, wait for a specific condition.
Use test.describe.configure({ mode: 'parallel' }) carefully. Parallel tests must be fully isolated — no shared database rows, no shared browser storage.
Record tests with playwright codegen to bootstrap selectors. It's not a substitute for thoughtful test design, but it speeds up initial selector discovery.
Why Playwright for TypeScript Projects?
Playwright was built by Microsoft — the same team behind TypeScript. Its API is fully typed, its fixture system is generic-first, and it ships with a code generator, trace viewer, and built-in test reporter. For TypeScript projects, it's the natural choice.
Other tools work, but Playwright's TypeScript integration is tighter:
playwright.config.ts(not.js)- Generic
test.extend<Fixtures>()for typed context - Auto-waiting that eliminates most
waitForcalls - Component testing mode for React, Vue, and Svelte via
@playwright/experimental-ct-react
Installation
npm init playwright@latestThe interactive setup creates playwright.config.ts, a tests/ directory, and example tests. Choose TypeScript when prompted.
Or install manually:
npm install --save-dev @playwright/test
npx playwright installConfiguration
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 4 : undefined,
reporter: process.env.CI ? 'github' : 'list',
use: {
baseURL: process.env.BASE_URL ?? 'http://localhost:3000',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
video: 'retain-on-failure',
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'mobile-safari',
use: { ...devices['iPhone 14'] },
},
],
webServer: {
command: 'npm run dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
timeout: 120_000,
},
});The webServer block starts your dev server before tests run and kills it after. In CI, set BASE_URL to your staging environment and remove webServer.
Page Object Models with TypeScript
Raw Playwright tests scatter selectors everywhere. Page Object Models (POMs) centralize selectors and interactions behind a typed API:
// tests/pages/LoginPage.ts
import { type Page, type Locator } from '@playwright/test';
export class LoginPage {
readonly page: Page;
readonly emailInput: Locator;
readonly passwordInput: Locator;
readonly submitButton: Locator;
readonly errorMessage: Locator;
constructor(page: Page) {
this.page = page;
this.emailInput = page.getByLabel('Email');
this.passwordInput = page.getByLabel('Password');
this.submitButton = page.getByRole('button', { name: 'Sign in' });
this.errorMessage = page.getByRole('alert');
}
async goto(): Promise<void> {
await this.page.goto('/login');
}
async login(email: string, password: string): Promise<void> {
await this.emailInput.fill(email);
await this.passwordInput.fill(password);
await this.submitButton.click();
}
async loginAndWait(email: string, password: string): Promise<void> {
await this.login(email, password);
await this.page.waitForURL('/dashboard');
}
}// tests/pages/DashboardPage.ts
import { type Page, type Locator } from '@playwright/test';
export class DashboardPage {
readonly page: Page;
readonly heading: Locator;
readonly userMenu: Locator;
readonly newProjectButton: Locator;
constructor(page: Page) {
this.page = page;
this.heading = page.getByRole('heading', { name: /dashboard/i });
this.userMenu = page.getByTestId('user-menu');
this.newProjectButton = page.getByRole('button', { name: 'New Project' });
}
async goto(): Promise<void> {
await this.page.goto('/dashboard');
}
async createProject(name: string): Promise<void> {
await this.newProjectButton.click();
await this.page.getByLabel('Project name').fill(name);
await this.page.getByRole('button', { name: 'Create' }).click();
await this.page.waitForURL(/\/projects\//);
}
}Using POMs in tests:
// tests/auth.test.ts
import { test, expect } from '@playwright/test';
import { LoginPage } from './pages/LoginPage';
import { DashboardPage } from './pages/DashboardPage';
test('successful login redirects to dashboard', async ({ page }) => {
const loginPage = new LoginPage(page);
const dashboardPage = new DashboardPage(page);
await loginPage.goto();
await loginPage.loginAndWait('user@example.com', 'password123');
await expect(dashboardPage.heading).toBeVisible();
});
test('invalid credentials show error message', async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.login('user@example.com', 'wrongpassword');
await expect(loginPage.errorMessage).toContainText('Invalid credentials');
});Typed Fixtures for Authentication
The Playwright fixture system is generic — you can define your own typed fixtures that extend the built-in test object:
// tests/fixtures.ts
import { test as base, type Page } from '@playwright/test';
import { LoginPage } from './pages/LoginPage';
import { DashboardPage } from './pages/DashboardPage';
export interface TestUser {
email: string;
password: string;
id: string;
}
interface MyFixtures {
loginPage: LoginPage;
dashboardPage: DashboardPage;
loggedInPage: Page;
testUser: TestUser;
}
export const test = base.extend<MyFixtures>({
loginPage: async ({ page }, use) => {
await use(new LoginPage(page));
},
dashboardPage: async ({ page }, use) => {
await use(new DashboardPage(page));
},
testUser: async ({}, use) => {
// Create user via API, clean up after
const user = await createTestUserViaAPI();
await use(user);
await deleteTestUserViaAPI(user.id);
},
loggedInPage: async ({ page, testUser }, use) => {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.loginAndWait(testUser.email, testUser.password);
await use(page);
},
});
export { expect } from '@playwright/test';Now your tests import from fixtures.ts instead of @playwright/test:
// tests/dashboard.test.ts
import { test, expect } from './fixtures';
test('dashboard shows user name', async ({ loggedInPage, testUser }) => {
await expect(loggedInPage.getByText(testUser.email)).toBeVisible();
});
test('can create a new project', async ({ loggedInPage }) => {
await loggedInPage.getByRole('button', { name: 'New Project' }).click();
await loggedInPage.getByLabel('Project name').fill('My Test Project');
await loggedInPage.getByRole('button', { name: 'Create' }).click();
await expect(loggedInPage.getByText('My Test Project')).toBeVisible();
});Storing Auth State
Re-logging in for every test is slow. Playwright can save browser storage state and reuse it:
// tests/global-setup.ts
import { chromium, type FullConfig } from '@playwright/test';
import { LoginPage } from './pages/LoginPage';
async function globalSetup(config: FullConfig): Promise<void> {
const browser = await chromium.launch();
const page = await browser.newPage();
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.loginAndWait('admin@example.com', 'adminpassword');
await page.context().storageState({ path: 'tests/.auth/admin.json' });
await browser.close();
}
export default globalSetup;// playwright.config.ts
export default defineConfig({
globalSetup: './tests/global-setup.ts',
projects: [
{
name: 'authenticated',
use: {
storageState: 'tests/.auth/admin.json',
},
},
{
name: 'unauthenticated',
// No storageState
},
],
});Login runs once per test suite, not per test. This can cut suite duration by 30–50% for auth-heavy applications.
Visual Regression Testing
Playwright's toHaveScreenshot captures and compares screenshots:
test('dashboard matches visual baseline', async ({ loggedInPage }) => {
await loggedInPage.goto('/dashboard');
await loggedInPage.waitForLoadState('networkidle');
// First run: creates baseline screenshot
// Subsequent runs: compares against baseline
await expect(loggedInPage).toHaveScreenshot('dashboard.png', {
maxDiffPixelRatio: 0.02, // Allow 2% pixel difference
});
});
test('button states look correct', async ({ page }) => {
await page.goto('/components');
const button = page.getByRole('button', { name: 'Submit' });
await expect(button).toHaveScreenshot('button-default.png');
await button.hover();
await expect(button).toHaveScreenshot('button-hover.png');
});Store baseline screenshots in git. Review and update them with npx playwright test --update-snapshots.
API Mocking for Flaky Dependencies
When testing against a real backend, third-party APIs cause flakiness. Mock them at the network level:
test('handles payment gateway timeout', async ({ page }) => {
await page.route('**/api/payments/**', async (route) => {
await route.fulfill({
status: 504,
contentType: 'application/json',
body: JSON.stringify({ error: 'Gateway Timeout' }),
});
});
await page.goto('/checkout');
await page.getByRole('button', { name: 'Pay Now' }).click();
await expect(page.getByRole('alert')).toContainText('Payment failed');
});This tests your error handling without needing a real payment gateway to time out.
CI Configuration
# .github/workflows/e2e.yml
name: E2E Tests
on:
push:
branches: [main]
pull_request:
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npx playwright install --with-deps
- run: npm run build
- name: Run E2E tests
run: npx playwright test
env:
BASE_URL: ${{ secrets.STAGING_URL }}
TEST_USER_EMAIL: ${{ secrets.TEST_USER_EMAIL }}
TEST_USER_PASSWORD: ${{ secrets.TEST_USER_PASSWORD }}
- name: Upload test results
if: failure()
uses: actions/upload-artifact@v4
with:
name: playwright-report
path: playwright-report/
retention-days: 7Debugging Failing Tests
Trace viewer — run with --trace on and open npx playwright show-trace:
npx playwright test --trace on
npx playwright show-reportThe trace viewer shows every action, network request, and DOM snapshot. Essential for CI failures you can't reproduce locally.
UI mode — interactive test runner:
npx playwright test --uiHeaded mode — watch the browser:
npx playwright test --headed --slowMo 500Debug mode — Playwright Inspector with step-by-step execution:
npx playwright test --debugCommon Mistakes
Using page.waitForTimeout(2000) — arbitrary sleeps make tests slow and brittle. Use waitForURL, waitForSelector, or waitForLoadState instead.
Hardcoding test credentials — use environment variables or test fixtures that create and clean up users.
Testing implementation details — test what the user sees and does, not internal state or component IDs.
Not cleaning up test data — every test that creates data should delete it in teardown, or use database transactions that roll back.
Running all tests headed locally — headed mode is for debugging specific tests, not your full suite. Headless is 3–5x faster.
Playwright with TypeScript gives you full type safety from test configuration to assertions. The fixture system makes test setup composable without beforeEach pyramid hell, and the trace viewer makes CI debugging tractable. Start with a few critical flows, add coverage as you discover pain points.