Automation

How to Structure a Playwright Framework (TypeScript)

By Emad Qasim · November 29, 2026 · 9 min read

Most Playwright projects start with one spec file and a few page.locator() calls. Six months later there are 200 tests, the same selector copied into 30 files, and a suite that fails at random when tests run in parallel. A little structure early on prevents all of that.

This is the layout I use for real projects, including my EventHub booking-app framework.

The folder structure

tests/
  api/              # API-only specs (request fixture, no browser)
  ui/               # UI specs, one folder or file per feature
  e2e/              # cross-layer journeys: book → verify → cancel
  setup/
    auth.setup.ts   # logs in once, saves storageState
src/
  api/              # typed API clients: AuthApi, EventsApi, BookingsApi
  pages/            # page objects: LoginPage, EventsPage, BookingsPage
  components/       # shared UI pieces: NavBar, Toast, ConfirmDialog
  fixtures/         # test.extend: clients, pages, seeded data + cleanup
  data/             # builders: unique titles, future dates, valid phones
  types/            # request/response types that mirror the API schema
playwright.config.ts
.env                # credentials (git-ignored)

The important idea is layers. Each layer knows only what it needs to:

  1. Specs describe behaviour. They contain no selectors and no URLs.
  2. Fixtures connect page objects and API clients to specs, and handle setup and teardown.
  3. Page objects and API clients are the only code that knows selectors and endpoints.
  4. Data builders produce unique, valid test data.

1. Page objects: selectors live here only

// src/pages/LoginPage.ts
import type { Page, Locator } from '@playwright/test';

export class LoginPage {
  readonly email: Locator;
  readonly password: Locator;
  readonly submit: Locator;

  constructor(private readonly page: Page) {
    this.email = page.getByLabel('Email');
    this.password = page.getByLabel('Password');
    this.submit = page.getByRole('button', { name: 'Sign in' });
  }

  async goto(): Promise<void> {
    await this.page.goto('/login');
  }

  async login(email: string, password: string): Promise<void> {
    await this.email.fill(email);
    await this.password.fill(password);
    await this.submit.click();
  }
}

Two rules keep page objects clean:

  • Methods do things or return data. They don’t assert. Assertions belong in the spec, where the reader expects them.
  • Prefer user-facing locators: getByTestId, getByRole and getByLabel come before CSS. Avoid XPath, styling class names, and nth() without a filter.

2. API clients: endpoints live here only

// src/api/EventsApi.ts
import type { APIRequestContext } from '@playwright/test';
import type { EventInput, EventResponse } from '../types/events';

export class EventsApi {
  constructor(private readonly request: APIRequestContext) {}

  async create(data: EventInput): Promise<EventResponse> {
    const res = await this.request.post('/api/events', { data });
    if (!res.ok()) throw new Error(`Create event failed: ${res.status()}`);
    return (await res.json()) as EventResponse;
  }

  async delete(id: number): Promise<void> {
    await this.request.delete(`/api/events/${id}`);
  }
}

The clients are typed against src/types, so a change to the API schema shows up as a compile error instead of a confusing test failure.

3. Data builders: unique and valid every time

// src/data/eventBuilder.ts
export function buildEvent(overrides: Partial<EventInput> = {}): EventInput {
  const inThirtyDays = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
  return {
    title: `QA-Event-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
    category: 'Conference',
    eventDate: inThirtyDays.toISOString(),
    price: 25,
    totalSeats: 50,
    ...overrides,
  };
}

With unique titles, parallel tests never collide. Future dates keep the data valid however long the suite lives. Need bulk data for data-driven tests? Use the test data generator.

4. Fixtures: setup, teardown, and no leftovers

This is where the structure pays off:

// src/fixtures/index.ts
import { test as base } from '@playwright/test';
import { EventsApi } from '../api/EventsApi';
import { EventDetailPage } from '../pages/EventDetailPage';
import { buildEvent } from '../data/eventBuilder';

type Fixtures = {
  eventsApi: EventsApi;
  eventDetailPage: EventDetailPage;
  seededEvent: EventResponse;
};

export const test = base.extend<Fixtures>({
  eventsApi: async ({ request }, use) => {
    await use(new EventsApi(request));
  },
  eventDetailPage: async ({ page }, use) => {
    await use(new EventDetailPage(page));
  },
  seededEvent: async ({ eventsApi }, use) => {
    const event = await eventsApi.create(buildEvent());
    await use(event);
    await eventsApi.delete(event.id); // runs even if the test fails
  },
});
export { expect } from '@playwright/test';

A test that asks for seededEvent gets a fresh event created through the API, and the event is deleted when the test ends, whether it passed or not.

5. Authenticate once

// tests/setup/auth.setup.ts
import { test as setup } from '@playwright/test';

setup('authenticate', async ({ page, request }) => {
  const res = await request.post('/api/auth/login', {
    data: { email: process.env.APP_EMAIL, password: process.env.APP_PASSWORD },
  });
  const { token } = await res.json();
  await page.goto('/');
  await page.evaluate((t) => localStorage.setItem('app_token', t), token);
  await page.context().storageState({ path: 'playwright/.auth/user.json' });
});

Then in playwright.config.ts, make the UI projects depend on it:

projects: [
  { name: 'setup', testMatch: /.*\.setup\.ts/ },
  {
    name: 'chromium',
    use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/user.json' },
    dependencies: ['setup'],
  },
],

Credentials come from environment variables, from a git-ignored .env file locally and from secrets in CI. Never hard-code them.

6. The spec: behaviour only

With everything else in place, the spec reads like a test case:

// tests/ui/booking.spec.ts
import { test, expect } from '../../src/fixtures';

test.describe('Booking', () => {
  test('booking tickets reduces available seats @smoke @ui', async ({ seededEvent, eventDetailPage }) => {
    await eventDetailPage.goto(seededEvent.id);
    await eventDetailPage.book({ quantity: 3 });

    await expect(eventDetailPage.bookingRef).toHaveText(/^EVT-[A-Z0-9]{6}$/);
    await expect(eventDetailPage.availableSeats).toHaveText(String(seededEvent.totalSeats - 3));
  });
});

The spec has no selectors, no URLs, no waitForTimeout and no cleanup code, and it passes when it runs alone, in any order, or in parallel.

7. CI on GitHub Actions

A minimal workflow installs dependencies and browsers, runs the suite with retries, and uploads the HTML report:

- run: npm ci
- run: npx playwright install --with-deps
- run: npx playwright test
  env:
    APP_EMAIL: ${{ secrets.APP_EMAIL }}
    APP_PASSWORD: ${{ secrets.APP_PASSWORD }}
- uses: actions/upload-artifact@v4
  if: always()
  with:
    name: playwright-report
    path: playwright-report/

In the config, set retries: process.env.CI ? 2 : 0, forbidOnly: !!process.env.CI and trace: 'on-first-retry'. When a test fails in CI you then get a full trace to debug, at almost no cost when it passes.

Checklist

  • Selectors appear only in page objects
  • Endpoints appear only in API clients
  • Every test creates and cleans up its own data
  • Login happens once, in a setup project
  • No waitForTimeout, only web-first assertions
  • Tests are tagged (@smoke, @regression, @api, @ui)
  • CI uploads the report and traces

FAQ

Do I need page objects with Playwright?

For a handful of tests, no. Once several specs touch the same page, yes. Page objects keep selectors in one place, so a UI change means one edit instead of twenty.

Should tests log in through the UI?

Only the test that checks the login page itself. Every other test should reuse a saved storageState from an auth setup project. It is faster and doesn't fail when the login page has a problem.

How do I keep parallel tests from clashing?

Each test creates its own data with unique names (add a timestamp or random suffix), asserts only on that data, and deletes it in fixture teardown. Never assert on absolute counts of shared records.