Playwright 03 ๐ญ Writing Your First Test โ test, expect, and page.goto
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
| Element | Signature |
|---|---|
| Test | test(name, async ({ page }) => { ... }) |
| Page fixture | { page } โ fresh tab per test |
| Context fixture | { context } โ fresh context per test |
| Browser fixture | { browser } โ shared per worker |
Navigation
| Call | Waits 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
| Matcher | Retries |
|---|---|
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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Assertion fails on slow page | Read-then-assert | Use web-first matcher |
| Navigation not complete | Missing await | Await page.goto |
| Flaky after data load | waitUntil: "load" too early | Use web-first assertion for the data |
| Test works only on localhost | Absolute URL | Use baseURL + relative path |
| Wrong element matched | Ambiguous selector | Use 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
| Item | Value |
|---|---|
| Test function | test(name, async ({ page }) => { ... }) |
| Page fixture | Fresh tab per test |
| Navigation | page.goto(url) |
| Default wait | load event |
| Web-first assertion | expect(locator).toMatcher() retries |
| Value assertion | expect(value).toMatcher() reads once |
| Relative URL | baseURL from config |
Key takeaways:
- Every action is awaited. Playwright’s actions return Promises, and the test must await them. A missing
awaitcauses 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.gotowaits for the load event by default. ThewaitUntiloption 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
baseURLmakes tests environment-independent. Relative URLs resolve against the config’sbaseURL, 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.
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!