Playwright First Test
A student pilot never flies a jumbo jet on the first lesson. That student starts with a small aircraft and a short flight path. A first Playwright test follows the same idea: open one page, check one simple fact, and build confidence before tackling complex scenarios.
The Goal of a First Test
This test opens a webpage and confirms the page title matches an expected value. A page title is the text shown on a browser tab, making it an easy and visible starting point.
What the Test Does
Start Test
|
v
Open Website
|
v
Read Page Title
|
v
Compare With Expected Title
|
v
Report Pass or Fail
Writing the Test File
Create a file named homepage.spec.js inside the tests folder, then add this code:
const { test, expect } = require('@playwright/test');
test('homepage shows correct title', async ({ page }) => {
await page.goto('https://example.com');
await expect(page).toHaveTitle(/Example Domain/);
});Breaking Down Every Line
The first line imports two tools from Playwright: test to define a test and expect to check results. The second line names the test with a short description that appears in reports. Inside the test, page.goto opens the given website in a real browser. The final line checks that the page title contains the text "Example Domain."
Running the Test
npx playwright test homepage.spec.jsPlaywright opens the browser behind the scenes, performs each step, and prints a result. A green checkmark and the word "passed" confirm success.
Watching the Test Run Visually
Beginners often want to see the browser open on screen instead of running invisibly. Add the headed option to watch every action happen live:
npx playwright test homepage.spec.js --headedMaking the Test Fail on Purpose
Change the expected title text to something incorrect, such as "Wrong Title," then run the test again. Playwright shows a red failure message describing exactly what it expected versus what it found. Seeing a failure message early builds comfort reading them later during real debugging.
Quick Practice Task
Pick any website you use often and write a test checking its page title. Run the test in headed mode to watch the browser open and close automatically.
Key Takeaways
- A first test should check one simple, visible fact.
- The test, expect, page.goto, and toHaveTitle pieces form the core pattern.
- Headed mode shows the browser opening live for easier learning.
- Reading a failure message carefully speeds up fixing real bugs later.
