Your First Playwright Test
Write your very first Playwright test from scratch. Learn the anatomy of a test file, understand async/await, and use page.goto and expect assertions.
Playwright Automation • Module 1 • Lesson 2
10 min read
What you'll learn
- Understand the structure of a Playwright test file
- Use page.goto to navigate to a URL
- Use expect with toHaveTitle to assert page state
- Write a complete test from scratch
Playwright AutomationlessonsJump to another lesson
Anatomy of a Test
Every Playwright test follows the same 5-line shape:
import { test, expect } from '@playwright/test';
test('homepage has the correct title', async ({ page }) => {
await page.goto('https://playwright.dev');
await expect(page).toHaveTitle(/Playwright/);
});
a Playwright test
5 fieldsimport:"{ test, expect }"
test():"'test name', callback"
async:"{ page } fixture"
action:"page.goto(...)"
assertion:"expect(...).toBe(...)"
What Happens When Playwright Runs
Start browser
2
page.goto()
Interact
Assert
Done!
Quick Check
Question 1 of 10 correct
What is the { page } argument in async ({ page }) => { ... } ?
async / await
Every page.* call and every expect() returns a Promise. You must await them so steps run in order.
Forgetting await (broken)
- page.goto(url) — fires off, doesn't wait
- page.click() — races against navigation
- Random, flaky failures
- Test might pass once, fail next run
Proper await (works)
- await page.goto(url) — waits for load
- await page.click() — runs after navigation
- Deterministic, consistent results
- Steps execute in the order you wrote them
VerdictRule: if a Playwright call returns a Promise, await it. Almost every page.* and expect() call qualifies.
// CORRECT — each step waits for the previous one
test('sequential steps', async ({ page }) => {
await page.goto('https://example.com');
await page.getByRole('link', { name: 'More' }).click();
await expect(page).toHaveURL(/more-info/);
});
The #1 Beginner Mistake
Practice: Complete the Test
Fill in the missing parts to complete this Playwright test.
import { test, expect } from '@playwright/test'; test('Playwright site has correct title', async ({ page }) => { await ('https://playwright.dev'); await expect(page).(/Playwright/); });
Try It: Write a Test in the Playground
Knowledge Check
Question 1 of 20 correct