Back To Blogs

Getting Started With Playwright: Your First Reliable Test in TypeScript

This guide takes you from an empty folder to a reliable Playwright test running in CI. It assumes basic JavaScript or TypeScript and Node.js installed.

1. Install

mkdir shop-tests && cd shop-tests
npm init playwright@latest

Accept TypeScript, a tests folder, and the GitHub Actions workflow. This installs @playwright/test, the browsers and an example config.

Run the example tests:

npx playwright test
npx playwright show-report

2. Configure a base URL

In playwright.config.ts:

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

export default defineConfig({
  testDir: './tests',
  retries: process.env.CI ? 1 : 0,
  use: {
    baseURL: 'https://your-app.example',
    trace: 'on-first-retry',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'mobile', use: { ...devices['iPhone 13'] } },
  ],
});

Now tests can call page.goto('/cart').

3. Write your first test

Test a behaviour a user cares about, such as removing an item updating the cart total:

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

test('removing an item updates the cart total', async ({ page }) => {
  await page.goto('/');

  await page.getByRole('button', { name: 'Add Ceramic mug to cart' }).click();
  await page.getByRole('button', { name: 'Add T-shirt to cart' }).click();
  await page.getByRole('link', { name: 'Cart' }).click();

  await expect(page.getByTestId('cart-total')).toHaveText('$37.00');

  await page
    .getByRole('listitem')
    .filter({ hasText: 'T-shirt' })
    .getByRole('button', { name: 'Remove' })
    .click();

  await expect(page.getByTestId('cart-total')).toHaveText('$12.00');
});

Note two things:

  • Locators by role and accessible name (getByRole) survive redesigns and also nudge the app towards accessibility
  • Web-first assertions (await expect(locator).toHaveText(...)) retry until they pass or time out, so no sleep() is needed

4. Run and debug

npx playwright test --ui          # interactive runner
npx playwright test --headed      # watch the browser
npx playwright test --debug       # step through
npx playwright codegen https://your-app.example   # record locators

When a test fails in CI, open the trace (npx playwright show-trace trace.zip) to see every action, DOM snapshot, network request and console message. It's the single most useful debugging feature.

5. Keep tests independent

Each test should create the state it needs and not depend on other tests:

test.beforeEach(async ({ page }) => {
  await page.goto('/');
});

For speed, create data through the API instead of clicking through the UI:

test('order appears in history', async ({ page, request }) => {
  const res = await request.post('/api/test/orders', { data: { items: ['mug'] } });
  expect(res.ok()).toBeTruthy();
  await page.goto('/orders');
  await expect(page.getByRole('row', { name: /Ceramic mug/ })).toBeVisible();
});

(The endpoint here is illustrative. Use whatever setup API your app provides.)

6. Sign in once, reuse the session

Use a setup project that signs in and saves storageState, then reuse it in other tests so you don't log in through the UI every time. See "Authentication" in the Playwright docs.

7. Run in CI

The generated GitHub Actions workflow installs browsers, runs the tests and uploads the HTML report as an artifact. Keep CI runs:

  • Fast: parallel workers, sharding for big suites
  • Deterministic: stable test data, no shared accounts between parallel tests
  • Informative: traces on retry, reports as artifacts

Reliability checklist

  • No hard waits (waitForTimeout) except to diagnose
  • Role, label or test ID locators, no long CSS chains
  • Each test independent and runnable alone
  • Assertions check user-visible outcomes
  • Retries only to collect traces, not to hide flakiness

What to automate next

Start with your app's smoke tests and money paths: sign in, the core action, checkout or booking. Then add regression tests for bugs that have escaped before.

Want ideas for high-value tests? Find the bugs by hand first in QAUnlocked Practice Labs, then write the Playwright test that would have caught each one. It's a great exercise and a great portfolio piece.

playwrighttypescripttest automationtutorial

Comments

0 Comments

Be the first to comment.