Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 35 ยท Getting Started

Your First Playwright Test

Create a Playwright project with npm init playwright, read playwright.config, write a test with page.goto and expect, run the CLI and open the HTML report.

Playwright is a test runner and a browser-control library in one package. You write ordinary async functions, ask for a page, and the runner starts a browser, runs your function and shuts everything down. This lesson covers the real setup, the first test, the commands you will use daily and the HTML report, and then builds a runnable stand-in that shows how a test receives its page and why every line starts with await.

Playwright installs browsers and needs a real machine, so the commands and files here are read-only. The stand-in at the end is a small model of the runner's fixture and await flow, written in plain Node.js for the site's runner. It is not Playwright.

Create a project

In an empty folder (or an existing project), run the initializer:

Terminal
# read-only
npm init playwright@latest

It asks a few questions: TypeScript or JavaScript, where to put tests (the default folder is tests), whether to add a GitHub Actions workflow, and whether to install the browsers. Afterwards you have:

TEXT
my-project/
  package.json
  playwright.config.ts
  tests/
    example.spec.ts
  tests-examples/       <- a longer demo, safe to delete

If you skip the browser download, fetch them later with npx playwright install. Playwright downloads its own copies of Chromium, Firefox and WebKit, so your tests do not depend on whatever browser is installed on the machine.

The configuration file

playwright.config.ts is where you set defaults. A trimmed version:

TypeScript
// playwright.config.ts (read-only)
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',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox', use: { ...devices['Desktop Firefox'] } },
    { name: 'webkit', use: { ...devices['Desktop Safari'] } },
  ],
  webServer: {
    command: 'npm run start',
    url: 'http://localhost:3000',
    reuseExistingServer: !process.env.CI,
  },
});

The pieces to know now:

  • testDir is where Playwright looks for files ending in .spec.ts or .test.ts (and the JavaScript equivalents).
  • use.baseURL lets page.goto('/login') resolve against your app.
  • projects run the same tests in several browsers or device setups.
  • webServer starts your app before the tests, and stops it afterwards.
  • retries reruns a failed test; use it carefully (Finding and Fixing Flaky Tests).

You will return to the configuration in Configuration and Environments.

Your first test

Create tests/home.spec.ts:

TypeScript
// tests/home.spec.ts (read-only)
import { test, expect } from '@playwright/test';

test('home page has a heading', async ({ page }) => {
  await page.goto('/');
  await expect(page.getByRole('heading', { level: 1 })).toContainText('Learn to code');
});

test('search filters lessons', async ({ page }) => {
  await page.goto('/');
  await page.getByPlaceholder('Search').fill('closures');
  await expect(page.getByRole('listitem')).toHaveCount(1);
  await expect(page.getByText('Closures in JavaScript')).toBeVisible();
});

Walk through it:

  • test(name, async ({ page }) => { ... }) defines a test. The curly braces in the parameter are destructuring: the runner passes an object of fixtures, and you take the one called page.
  • page is a fresh browser tab, created for this test alone, in a clean browser context with no leftover cookies or storage.
  • await page.goto('/') navigates and waits for the page to load.
  • page.getByRole(...), getByPlaceholder and getByText create locators, descriptions of how to find elements. They are lazy: nothing is searched until you use them (Locators in Playwright).
  • await locator.fill(...) types into a field. Before it acts, Playwright waits until the element is attached, visible, stable and enabled.
  • await expect(locator).toHaveCount(1) is a web-first assertion: it retries until it is true or the timeout passes.

Every step is awaited because each one is a message to a browser that finishes later. Forgetting an await is the most common beginner bug; you will see why in the stand-in below.

Running tests

Terminal
# read-only
npx playwright test                       # all tests, headless, in every project
npx playwright test tests/home.spec.ts    # one file
npx playwright test -g "search"           # tests whose title matches
npx playwright test --project=chromium    # one browser only
npx playwright test --headed              # show the browser window
npx playwright test --ui                  # interactive UI mode
npx playwright test --debug               # step through with the inspector
npx playwright show-report                # open the last HTML report

By default tests run in parallel across worker processes, headless, and the console shows a summary line. With reporter: 'html', a failing run also writes a report folder; npx playwright show-report opens it in your browser. For each test the report lists the steps, the error with a code frame, and any attached screenshot, video or trace (Traces, Videos and Reports).

flowchart LR
  R["Runner<br/>npx playwright test"] --> W["Worker process"]
  W --> Br["New browser context<br/>and page"]
  Br --> T["Your test(page)"]
  T --> A["Result and artifacts"]
  A --> H["HTML report"]

For each test the runner creates a worker, a clean context and a page, runs your function, then collects results into a report.

A model of fixtures and await

In the stand-in below, runTest plays the part of the runner. It builds a fake page before the test, passes it in, waits for the test to finish and tears the page down afterwards. The fake page answers each call after a short delay, as a real browser would, and expect(...).toHaveText polls until it matches or times out.

Node.js A mini Playwright-style runner with fixtures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at what the model shows:

  • The first test passes even though the heading appears after goto returns, because the assertion polls. Nothing in the test says "wait".
  • Each test gets its own page, set up before and closed after, so tests cannot leak state into each other. That is what Playwright fixtures give you.
  • Real Playwright does this with a much richer fixture system (Hooks, Fixtures and Custom Commands) and a real browser behind page.

To see why await matters, imagine deleting it before page.fill(...) in the model: the next line would run immediately, before the field was filled. In real Playwright the effect is similar, and tests become flaky or pass without checking anything.

Habits to build from day one

  • Await every Playwright call that returns a promise: actions, navigation and expect.
  • Choose locators by role, label and text first; you will see why in Writing Selectors That Do Not Break.
  • Never use page.waitForTimeout() to wait for things. Let auto-waiting and web-first assertions do it (Auto-Waiting in Playwright).
  • Keep tests independent. Each gets a fresh page, so rely on that.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which command creates a new Playwright project with a config file and an example test?

    npm init playwright@latest asks a few questions and then writes playwright.config, an example spec and the package setup.
  2. 2. In test('x', async ({ page }) => { ... }), where does page come from?

    Playwright passes fixtures such as page to your test function. Each test gets a fresh page in a clean browser context.
  3. 3. What is special about await expect(locator).toHaveText('Hi')?

    Playwright's expect with locators is a web-first assertion: it polls until the condition holds or times out, so you do not add manual waits.
  4. 4. Which command shows the HTML report from the last run?

    npx playwright show-report serves the generated HTML report in your browser.
  5. 5. What happens if you forget await before an action like page.click()?

    Actions return promises. Without await, the next line runs immediately, so ordering and assertions can go wrong.

Summary

  • npm init playwright@latest creates the config, an example test and, optionally, the browsers.
  • playwright.config sets testDir, baseURL, projects, retries, reporter and webServer.
  • A test is test(name, async ({ page }) => ...); the runner supplies a fresh page fixture for each test.
  • Locators are lazy; actions auto-wait; expect with locators retries.
  • Run with npx playwright test, filter by file, -g or --project, and open the report with npx playwright show-report.
  • The model runner is a stand-in showing fixtures and await flow, not the real Playwright.

Next: Selecting Elements in Cypress