| | |

Playwright 03 ๐ŸŽญ Writing Your First Test โ€” test, expect, and page.goto

โฑ๏ธ Estimated read: 9 min | |

A Playwright test is a function that receives a fixture object and performs actions on a page. The test function declares the case, the { page } fixture provides a fresh browser tab, page.goto() navigates to a URL, and expect() with a web-first assertion checks the result. The structure is deliberately minimal: no setup code, no teardown code, no manual browser launch. The test runner creates the browser, the context, and the page before the test runs, and discards them after it ends.

This chapter covers the anatomy of a Playwright test, the page.goto navigation, and the assertion style that distinguishes Playwright from a generic assertion library. The sections that follow walk through the test signature, the page fixture, and the web-first assertions that retry until the condition is met.

Key point: A Playwright test is test(name, async ({ page }) => { ... }); the page fixture is created fresh for every test, page.goto navigates and waits for the load event, and expect(locator) auto-retries until the assertion passes or the timeout expires.


a. The test signature and the page fixture

The test function takes a name and an async function. The function receives a fixtures object; the page fixture is the most common and represents a single tab in a fresh browser context. Playwright creates the browser, the context, and the page before the test, and closes them after it, so the test body contains only the actions and assertions.

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

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

The fixture is destructured in the parameter list. A test that needs the context as well as the page writes async ({ page, context }) => { ... }; a test that needs the browser writes async ({ browser }) => { ... }. The fixtures are created on demand and torn down in reverse order, which is why a test that creates its own contexts inside a single testโ€”for a multi-user scenarioโ€”still has the default page available.

The test function is async. Every Playwright action returns a Promise, and the test must await it. A test that calls page.goto() without await proceeds before the navigation completes, and the assertion that follows runs against the previous page state. The await is not optional; it is the mechanism that sequences the actions.


b. page.goto and navigation

page.goto(url) navigates the page to the given URL and waits for the load event by default. The second argument is an options object with waitUntil and timeout:

await page.goto("/login"); // relative to baseURL in config
await page.goto("https://example.com", { waitUntil: "networkidle" });
await page.goto("/slow", { timeout: 60_000 });

The waitUntil values are "load" (default), "domcontentloaded", "networkidle", and "commit". The "networkidle" value waits for no network connections for at least 500ms, which is useful for pages that load data after the initial HTML, but it is discouraged for pages with long-polling or websockets because the network never becomes idle . The default "load" is usually sufficient, and the auto-waiting assertions handle the rest.

The baseURL in playwright.config.ts makes relative URLs work. A test that calls page.goto("/login") navigates to ${baseURL}/login, which lets the same test run against localhost, staging, and production by changing the config, not the test .

// playwright.config.ts
export default defineConfig({
  use: {
    baseURL: "http://localhost:3000",
  },
});

page.goto throws if the navigation failsโ€”a 404, a connection refused, a timeout. The test fails with the error, which is the correct behavior for a navigation that should have succeeded. For a test that expects a failed navigation, the assertion is on the response status, not on a caught exception.


c. Web-first assertions and auto-retrying

The expect imported from @playwright/test is not the same expect as Vitest or Jest. It includes the generic matchers (toBe, toEqual) but adds web-first assertions that retry until the condition is met or the timeout expires . The difference matters: expect(await page.textContent("h1")).toBe("Welcome") reads the text once and fails if it is not yet “Welcome”; expect(page.getByRole("heading")).toHaveText("Welcome") retries until the heading’s text is “Welcome” or the timeout expires.

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

test("login flow", async ({ page }) => {
  await page.goto("/login");

  // Actions auto-wait for the element to be actionable
  await page.getByLabel("Email").fill("user@example.com");
  await page.getByLabel("Password").fill("password123");
  await page.getByRole("button", { name: "Sign in" }).click();

  // Web-first assertion: retries until the heading appears
  await expect(page.getByRole("heading", { name: "Dashboard" })).toBeVisible();

  // Web-first assertion: retries until the URL matches
  await expect(page).toHaveURL(/\/dashboard/);
});

The web-first matchers include toBeVisible, toBeHidden, toHaveText, toContainText, toHaveValue, toHaveURL, toHaveTitle, toHaveCount, toBeEnabled, toBeDisabled, toBeChecked, and toHaveAttribute . Each one retries, and each one fails with a message that includes the locator, the expected value, and the actual value at the time of the timeout.

The expect from @playwright/test also supports the generic matchers for values that are not locators: expect(response.status()).toBe(200), expect(await page.title()).toContain("Dashboard"). The rule is that a locator assertion uses the web-first matcher and retries; a value assertion reads the value once and does not.


Complete Example Session

// ============================================
// PART 1: THE CONFIG (BASE URL)
// ============================================
// playwright.config.ts
import { defineConfig } from "@playwright/test";

export default defineConfig({
  use: {
    baseURL: "http://localhost:3000",
    trace: "on-first-retry",
  },
});

// ============================================
// PART 2: THE FIRST TEST
// ============================================
// tests/home.spec.ts
import { test, expect } from "@playwright/test";

test("home page shows the welcome heading", async ({ page }) => {
  await page.goto("/");
  await expect(page.getByRole("heading", { name: "Welcome" })).toBeVisible();
});

// ============================================
// PART 3: A TEST WITH ACTIONS
// ============================================
test("user can search", async ({ page }) => {
  await page.goto("/");

  await page.getByRole("searchbox").fill("playwright");
  await page.getByRole("button", { name: "Search" }).click();

  await expect(page.getByRole("listitem")).toHaveCount(3);
  await expect(page.getByText("playwright")).toBeVisible();
});

// ============================================
// PART 4: THE PAGE FIXTURE IS FRESH
// ============================================
// Test 1 runs in context A.
// Test 2 runs in context B.
// Cookies from Test 1 are not visible in Test 2.

The parts covered the base URL config, the first test with a web-first assertion, a test with actions and a count assertion, and the isolation that the page fixture provides.


Quick Reference

Test Function

ElementSignature
Testtest(name, async ({ page }) => { ... })
Page fixture{ page } โ€” fresh tab per test
Context fixture{ context } โ€” fresh context per test
Browser fixture{ browser } โ€” shared per worker

Navigation

CallWaits For
page.goto(url)load event
page.goto(url, { waitUntil: "domcontentloaded" })DOM parsed
page.goto(url, { waitUntil: "networkidle" })500ms of no network
page.goto(url, { timeout: 60000 })Custom timeout

Web-First Assertions

MatcherRetries
toBeVisible()Yes
toHaveText()Yes
toContainText()Yes
toHaveURL()Yes
toHaveCount()Yes
toBeEnabled()Yes
toHaveValue()Yes

Best Practices

โœ… Do This:

// Await every action
await page.goto("/");                                         // โœ…

// Use web-first assertions
await expect(page.getByRole("heading")).toBeVisible();        // โœ…

// Use relative URLs with baseURL
await page.goto("/login");                                    // โœ…

// Use role-based locators
page.getByRole("button", { name: "Submit" })                  // โœ…

โŒ Don’t Do This:

// Missing await
page.goto("/"); // proceeds before navigation                 // โŒ

// Read-then-assert instead of web-first
expect(await page.textContent("h1")).toBe("Welcome");         // โŒ (no retry)

// Hard-coded absolute URL
await page.goto("http://localhost:3000/login");               // โŒ

// Use CSS selectors when role locators work
page.locator("button.submit-btn")                             // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Assertion fails on slow pageRead-then-assertUse web-first matcher
Navigation not completeMissing awaitAwait page.goto
Flaky after data loadwaitUntil: "load" too earlyUse web-first assertion for the data
Test works only on localhostAbsolute URLUse baseURL + relative path
Wrong element matchedAmbiguous selectorUse role-based locator

Real-World Examples

1. Basic test

test("has title", async ({ page }) => {
  await page.goto("/");
  await expect(page).toHaveTitle(/My App/);
});

2. Fill and click

await page.getByLabel("Email").fill("a@b.com");
await page.getByRole("button", { name: "Submit" }).click();

3. Visible assertion

await expect(page.getByText("Saved")).toBeVisible();

4. URL assertion

await expect(page).toHaveURL(/\/dashboard/);

5. Count assertion

await expect(page.getByRole("listitem")).toHaveCount(3);

6. Relative navigation

await page.goto("/login");

7. Custom timeout

await page.goto("/slow", { timeout: 60_000 });

8. Wait for network idle

await page.goto("/", { waitUntil: "networkidle" });

9. Response status

const response = await page.goto("/api");
expect(response?.status()).toBe(200);

10. Value assertion

await expect(page.getByLabel("Email")).toHaveValue("a@b.com");

Visual

Test Lifecycle

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Runner creates browser (shared per worker)             โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  Creates context (fresh per test)                       โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  Creates page (fresh per test)                          โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  Test body runs                                         โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  Context and page closed                                โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Web-First vs Read-Then-Assert

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  WEB-FIRST                                              โ”‚
โ”‚  expect(locator).toHaveText("X")                        โ”‚
โ”‚    โ†’ retries until text is "X" or timeout               โ”‚
โ”‚                                                         โ”‚
โ”‚  READ-THEN-ASSERT                                       โ”‚
โ”‚  expect(await locator.textContent()).toBe("X")          โ”‚
โ”‚    โ†’ reads once, fails immediately if not ready         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Navigation and baseURL

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Config: use: { baseURL: "http://localhost:3000" }      โ”‚
โ”‚                                                         โ”‚
โ”‚  Test: await page.goto("/login")                        โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  Navigates to http://localhost:3000/login               โ”‚
โ”‚                                                         โ”‚
โ”‚  Change the config, not the tests, to switch envs.      โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Auto-Waiting Action

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  page.getByRole("button").click()                       โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  Wait: visible, stable, enabled, not obscured           โ”‚
โ”‚         โ”‚                                               โ”‚
โ”‚         โ–ผ                                               โ”‚
โ”‚  Click                                                  โ”‚
โ”‚                                                         โ”‚
โ”‚  If not actionable: retry until timeout                 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Test functiontest(name, async ({ page }) => { ... })
Page fixtureFresh tab per test
Navigationpage.goto(url)
Default waitload event
Web-first assertionexpect(locator).toMatcher() retries
Value assertionexpect(value).toMatcher() reads once
Relative URLbaseURL from config

Key takeaways:

  • Every action is awaited. Playwright’s actions return Promises, and the test must await them. A missing await causes the test to proceed before the action completes .
  • The page fixture is fresh per test. The runner creates a context and a page before the test and closes them after, so no state leaks between tests .
  • page.goto waits for the load event by default. The waitUntil option changes what is awaited, and "networkidle" is discouraged for pages with long-polling .
  • Web-first assertions retry; value assertions do not. expect(locator).toBeVisible() retries until the element appears. expect(await page.textContent(...)).toBe(...) reads once and fails immediately if the value is not ready .
  • The baseURL makes tests environment-independent. Relative URLs resolve against the config’s baseURL, so the same test runs against localhost, staging, or production by changing the config, not the test code .

Remember: A Playwright test is a sequence of awaited actions followed by web-first assertions. The page fixture is created fresh for the test, page.goto navigates to the URL, and the assertions retry until the condition is met. Use role-based locators, relative URLs with baseURL, and web-first assertions for anything that reads from the DOM. The test should read like the user’s steps, and the waits should be implicit in the actions and assertions, not explicit waitForTimeout calls.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!