Playwright tutorial: end-to-end testing from scratch
By Flavio
Updated
Tagged: Node.js
Learn Playwright end-to-end testing from scratch: install it, write resilient tests, handle login, mock APIs, debug failures, and run everything in CI.
Playwright lets you test a web app inside a real browser. It opens pages, fills out forms, clicks buttons, and checks what ends up on screen, following the same path a real user takes.
This is called end-to-end testing, or E2E testing. A unit test checks one function in isolation, while an E2E test checks a complete user flow from start to finish. For example, you can test that a visitor can:
- open the signup page
- create an account
- log in
- add a product to the cart
- complete the checkout
A flow like that crosses your frontend, backend, database, and browser code all at once, so it catches bugs unit tests miss. Playwright bundles the browser automation library, a test runner, assertions, reports, debugging tools, and support for Chromium, Firefox, and WebKit in one place.
Let’s get it installed and write a real test suite.
Install Playwright
Run the official initializer inside your project directory:
npm init playwright@latest
It’ll ask you a few quick questions:
- whether you want JavaScript or TypeScript
- where to put your tests
- whether you want a GitHub Actions workflow
- whether to install the browser binaries right away
I use TypeScript for tests even when the app itself is plain JavaScript. Having the editor catch misspelled methods and invalid options before I even run the suite saves a lot of time.
Once it finishes, you’ll have a folder structure similar to this:
playwright.config.ts
tests/
example.spec.ts
The initializer also adds @playwright/test to your dev dependencies. The separate playwright package is just the browser automation library, while @playwright/test layers on the test runner, assertions, fixtures, retries, projects, and reports. For testing applications, @playwright/test is the one you want.
Write your first test
Every Playwright test follows three steps:
- Open a page
- Perform an action
- Check the result
Create tests/homepage.spec.ts with a simple check:
import { test, expect } from '@playwright/test'
test('homepage shows the site title', async ({ page }) => {
await page.goto('https://flaviocopes.com/')
await expect(
page.getByRole('heading', { level: 1 })
).toBeVisible()
await expect(page).toHaveTitle(/Flavio Copes/)
})
test() defines one test, and Playwright passes a page object to the callback representing a single browser tab. Inside, page.goto() opens the URL, getByRole() finds the heading, and expect() verifies that the heading is visible and the page title contains the expected text. Because every browser operation is asynchronous, each one uses await.
Run the test from your terminal:
npx playwright test
Playwright runs headless by default, meaning the browser runs in the background with no visible window. Headless mode is fast and works well in CI, though it helps to watch the browser at first by passing --headed:
npx playwright test --headed
Run one test
Once your suite grows beyond a handful of files, you won’t want to run everything every time you edit one test.
To run a single file, pass its path:
npx playwright test tests/homepage.spec.ts
To filter tests by a word in their title:
npx playwright test -g "homepage"
You can also target just one browser project:
npx playwright test --project=chromium
While debugging, you can temporarily isolate a single test with test.only():
test.only('homepage shows the site title', async ({ page }) => {
await page.goto('/')
})
Just be careful not to leave test.only() behind when you commit, or CI will run that single test and quietly skip the rest. We’ll configure CI to reject .only a bit later.
Configure your app URL
Hardcoding the full URL in every test gets repetitive fast. Set a baseURL in playwright.config.ts instead:
import { defineConfig } from '@playwright/test'
export default defineConfig({
use: {
baseURL: 'http://localhost:3000',
},
})
Now your tests can use relative URLs and Playwright will combine each path with the base URL automatically:
await page.goto('/')
await page.goto('/login')
await page.goto('/products')
You can also let Playwright start your app before the tests run:
import { defineConfig } from '@playwright/test'
export default defineConfig({
use: {
baseURL: 'http://localhost:3000',
},
webServer: {
command: 'npm run dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
},
})
Playwright runs npm run dev and waits until the URL responds before starting the suite. With reuseExistingServer enabled, it hooks into your local dev server if one is already running, while CI always boots a clean server. That lets you run the full suite with one command.
Find elements with locators
A locator tells Playwright how to find an element on the page. Good locators keep your tests readable and stable, while weak ones break whenever the HTML shifts.
My advice is to look up elements the same way a user or screen reader would. For a button, use its role and visible name:
page.getByRole('button', { name: 'Create account' })
For a form field, grab it by its label:
page.getByLabel('Email')
For visible content, match the text on screen:
page.getByText('Your order is confirmed')
Here are the main locator methods Playwright provides and when each one fits best:
| Locator | Good for |
|---|---|
getByRole() | Buttons, links, headings, and other accessible elements |
getByLabel() | Form fields with labels |
getByText() | Visible text |
getByPlaceholder() | Inputs identified by placeholder text |
getByAltText() | Images with alternative text |
getByTestId() | Elements with a stable test ID |
Suppose your page has a form like this:
<label for="email">Email</label>
<input id="email" type="email">
<button>Create account</button>
With user-facing locators, the test reads like a plain description of what the user does:
await page.getByLabel('Email').fill('[email protected]')
await page.getByRole('button', { name: 'Create account' }).click()
Avoid fragile CSS selectors
Playwright does let you use CSS selectors:
page.locator('.signup-form > div:nth-child(2) > button')
The catch is that a selector like this knows too much about your HTML structure. Wrap that button in a new element or move it somewhere else and the test breaks, even though the user flow still works fine.
Locating the button by its role and name holds up much better:
page.getByRole('button', { name: 'Create account' })
Every so often an element won’t have a useful role, label, or text. In those cases, add a test ID attribute to the element:
<div data-testid="cart-total">$42.00</div>
Then locate it with getByTestId():
page.getByTestId('cart-total')
I use test IDs as an explicit fallback when user-facing locators aren’t enough. Don’t put them on every element, though, because accessible locators pull double duty by verifying that your interface exposes proper names and roles.
Understand strict locators
Playwright expects any locator you act on to match exactly one element. If the page has two “Delete” buttons, a broad locator like this is ambiguous:
page.getByRole('button', { name: 'Delete' })
Instead of guessing which button you meant, Playwright fails the test. Narrow the locator down to the specific product you want:
const product = page
.getByRole('listitem')
.filter({ hasText: 'JavaScript Handbook' })
await product.getByRole('button', { name: 'Delete' }).click()
Here Playwright finds the list item containing the book title, then clicks the Delete button inside it. You could chain .first() or .nth(1) instead, but that depends on item order. A scoped locator stays clear about which item you want even if the list changes.
Fill forms and click buttons
Most tests rely on the same small set of actions.
Fill in a text field:
await page.getByLabel('Name').fill('Flavio Copes')
Select an option from a dropdown:
await page.getByLabel('Country').selectOption('IT')
Check a checkbox:
await page.getByLabel('Accept the terms').check()
Upload a file:
await page
.getByLabel('Profile photo')
.setInputFiles('tests/files/avatar.png')
Press a key:
await page.getByLabel('Search').press('Enter')
Hover over an element:
await page.getByRole('button', { name: 'Account' }).hover()
Before running any of these actions, Playwright automatically checks that the target is ready. Before clicking, it waits for the element to exist in the DOM, become visible, stop moving, receive pointer events, and become enabled. This is called auto-waiting, and it eliminates a lot of timing headaches out of the box.
Let Playwright wait
Web pages update asynchronously. A click might kick off a request, show a message 300 milliseconds later, or enable a button after validation finishes.
It’s tempting to drop in a manual sleep:
await page.waitForTimeout(1000)
Fixed pauses lose both ways. If the page responds in 100 milliseconds, your test wastes 900 milliseconds sitting idle; if CI takes 1200 milliseconds on a slow runner, the test still fails.
Wait for the result you care about instead:
await page.getByRole('button', { name: 'Save' }).click()
await expect(page.getByText('Changes saved')).toBeVisible()
Playwright retries the assertion until the message appears or the timeout expires. Waiting for a state instead of guessing a number of milliseconds makes tests both faster and much more reliable.
Use web-first assertions
Playwright includes assertions built specifically for web pages, and they retry automatically until they pass or time out.
Check that an element is visible:
await expect(page.getByText('Welcome back')).toBeVisible()
Check its exact text:
await expect(page.getByTestId('cart-total')).toHaveText('$42.00')
Check how many items are in a list:
await expect(page.getByRole('listitem')).toHaveCount(3)
Check an input’s value:
await expect(page.getByLabel('Email')).toHaveValue('[email protected]')
Check the current URL:
await expect(page).toHaveURL('/dashboard')
Check the page title:
await expect(page).toHaveTitle(/Dashboard/)
Always await these assertions so Playwright can retry them.
To see the difference, compare reading the text once and asserting on a plain string:
expect(await page.getByTestId('status').textContent()).toBe('Ready')
against passing the locator directly to expect():
await expect(page.getByTestId('status')).toHaveText('Ready')
The first version grabs the value once and can easily run too early. The second keeps checking until the status becomes Ready. Reach for Playwright’s web-first assertions whenever one exists for what you’re checking.
Write a complete user-flow test
Let’s put locators, actions, and assertions together in a full flow. Imagine a small online bookstore where a visitor adds a book to the cart and starts checkout:
import { test, expect } from '@playwright/test'
test('add a book to the cart', async ({ page }) => {
await page.goto('/books')
const book = page
.getByRole('article')
.filter({ hasText: 'The JavaScript Handbook' })
await book.getByRole('button', { name: 'Add to cart' }).click()
await expect(page.getByTestId('cart-count')).toHaveText('1')
await page.getByRole('link', { name: 'Cart' }).click()
await expect(page).toHaveURL('/cart')
await expect(
page.getByRole('heading', { name: 'Your cart' })
).toBeVisible()
await expect(page.getByText('The JavaScript Handbook')).toBeVisible()
})
Notice that this test doesn’t know or care which JavaScript framework powers the page. It only checks what the user sees and does, so you could rewrite the entire frontend and keep the exact same test as long as the behavior stays the same.
Group tests and share setup
Tests for the same area of an app usually start on the same page. Group them with test.describe() and put the shared setup inside test.beforeEach():
import { test, expect } from '@playwright/test'
test.describe('cart', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/cart')
})
test('starts empty', async ({ page }) => {
await expect(page.getByText('Your cart is empty')).toBeVisible()
})
test('has a checkout button', async ({ page }) => {
await expect(
page.getByRole('button', { name: 'Checkout' })
).toBeVisible()
})
})
The hook runs before every test in the group. Keep each test self-contained, and don’t use one test to set up data for the next one.
Every test gets a clean browser context
Playwright creates a new browser context for every test, which acts like a fresh browser profile with its own cookies, local storage, session, and pages. One test can’t leak login cookies into another.
Because contexts are cheap, Playwright keeps the browser process open and still gives you full isolation without launching a brand-new browser for every test. That matters when tests run in parallel, and it lets you run any single test on its own without first running five others.
Browser isolation won’t help if two tests touch the same server-side data, though. When tests share a backend, give each one unique data or separate test accounts, like generating a unique email:
test('create an account', async ({ page }) => {
const email = `flavio+${Date.now()}@playwright.test`
await page.goto('/signup')
await page.getByLabel('Email').fill(email)
await page.getByLabel('Password').fill('test-password-123')
await page.getByRole('button', { name: 'Create account' }).click()
await expect(page).toHaveURL('/dashboard')
})
That keeps parallel test runs from fighting over the same account.
Test several browsers
Playwright supports Chromium, Firefox, and WebKit out of the box. Configure them as projects in your config file:
import { defineConfig, devices } from '@playwright/test'
export default defineConfig({
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
],
})
Now npx playwright test runs your suite across all three browsers. While developing locally, stick to Chromium for fast feedback and let CI run the full matrix:
npx playwright test --project=chromium
WebKit isn’t full Safari, since it’s the underlying engine, yet it catches plenty of Safari-specific rendering and behavior issues without requiring a Mac CI runner.
Test a mobile viewport
Projects can also emulate mobile devices. Add a mobile project to your config:
{
name: 'mobile-chrome',
use: {
...devices['Pixel 7'],
},
}
Playwright applies the device’s viewport, user agent, touch support, and pixel ratio automatically, so every test run catches broken mobile navigation, awkward forms, and responsive layout issues. Pair it with a quick check on a real phone when you’re shipping mobile-heavy changes.
Build a practical configuration
Here’s a solid starting playwright.config.ts for a real project:
import { defineConfig, devices } from '@playwright/test'
export default defineConfig({
testDir: './tests',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: 'html',
use: {
baseURL: 'http://localhost:3000',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
],
webServer: {
command: 'npm run dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
},
})
A few of these options are worth calling out:
forbidOnlyfails CI if a test still hastest.only()in it.retriesretries failed tests twice in CI, while local runs stay at zero retries so failures show up right away.workerskeeps CI at one worker for stability; you can bump it up later if the suite gets slow.tracerecords a trace on the first retry, including every step, DOM snapshot, network request, console message, and screenshot.screenshotsaves a screenshot whenever a test fails.
Start with a lean setup like this and adjust it as your suite grows.
Reuse an authenticated session
Logging in through the UI before every test slows down your suite fast. Instead, Playwright can log in once, save the browser’s cookies and local storage, and reuse that state across tests.
First, ignore the authentication file by adding this path to .gitignore:
playwright/.auth
That file can hold sensitive session cookies, so never commit it to your repo.
Next, create tests/auth.setup.ts to perform the login and save the state:
import { test as setup, expect } from '@playwright/test'
const authFile = 'playwright/.auth/user.json'
setup('authenticate', async ({ page }) => {
await page.goto('/login')
await page.getByLabel('Email').fill(process.env.TEST_USER_EMAIL!)
await page.getByLabel('Password').fill(process.env.TEST_USER_PASSWORD!)
await page.getByRole('button', { name: 'Log in' }).click()
await expect(page).toHaveURL('/dashboard')
await page.context().storageState({ path: authFile })
})
Then add a setup project and make your browser project depend on it:
import { defineConfig, devices } from '@playwright/test'
export default defineConfig({
projects: [
{
name: 'setup',
testMatch: /.*\.setup\.ts/,
},
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
storageState: 'playwright/.auth/user.json',
},
dependencies: ['setup'],
},
],
})
The setup test logs in and writes the state file, and your Chromium tests start already authenticated. Keep a small separate test for the login flow itself, and if parallel tests edit shared profile data, give them separate accounts so they don’t step on each other.
Mock an API response
Your tests don’t always have to hit the real backend. Playwright can intercept network requests and return controlled data, which is handy for error states that are tough to reproduce on demand.
Here’s how you can mock a products endpoint:
test('shows an empty products message', async ({ page }) => {
await page.route('**/api/products', async route => {
await route.fulfill({
json: [],
})
})
await page.goto('/products')
await expect(page.getByText('No products found')).toBeVisible()
})
Register the route before opening the page, since your app might fire that request the moment it loads.
You can use the same approach to simulate a server error:
await page.route('**/api/products', async route => {
await route.fulfill({
status: 500,
json: { error: 'Server unavailable' },
})
})
After that, assert that the page displays a helpful error message.
Mocking makes tests predictable, though it also removes part of your real system from the check. Keep at least a few tests running against the real API for your most critical flows so backend bugs don’t slip through.
Test visual changes
Playwright can compare a page or a single element against a saved reference screenshot. You add a visual assertion like this:
test('homepage layout', async ({ page }) => {
await page.goto('/')
await expect(page).toHaveScreenshot('homepage.png')
})
The first time you run it, Playwright reports that the reference image is missing and generates one for you. Open that image, make sure it looks right, and commit it to your repository so later runs have a baseline to compare against.
When an intentional design change breaks the match, update the saved snapshots:
npx playwright test --update-snapshots
Keep in mind that visual diffs are sensitive to operating systems, font rendering, animations, and dynamic content. Run them in a consistent environment, hide timestamps, turn off animations, and wait for fonts to load before taking the screenshot. Save visual tests for layouts where appearance matters instead of turning every page into a full-page screenshot test.
Generate a test with codegen
If you don’t want to write every locator by hand, Playwright can watch your browser actions and generate test code as you go. Start codegen from the terminal:
npx playwright codegen http://localhost:3000
This opens two windows: one running your app, and another displaying the generated code live while you click through the flow.
Codegen is great for discovering locators and putting together a quick first draft, though I never commit its output unchanged. Once you stop recording, clean it up so it tests what the user should be able to do rather than just replaying a raw list of clicks:
- rename the test so it describes user behavior
- delete unnecessary steps
- replace weak locators
- add assertions
- split long recordings into focused tests
Debug with UI Mode
When a test breaks, UI Mode is usually the easiest way to develop and debug your Playwright tests. Start it with:
npx playwright test --ui
From there you can filter the suite, run a single test, inspect network requests, and scrub through the timeline to see the page right before and after every action without repeating the test by hand.
If you prefer stepping through code one line at a time, you can open the Playwright Inspector instead to pause, resume, and inspect locators live:
npx playwright test --debug
You can also debug a single test on its own:
npx playwright test tests/cart.spec.ts --debug
Whenever I’m tracking down a failure, I follow the same workflow:
- Run the failing test in UI Mode
- Inspect the first step that behaves unexpectedly
- Check the locator and page state at that moment
- Fix the underlying cause
- Run the test several times to make sure it holds up
Looking only at the final error often isn’t enough, because the real mistake usually happened at the first step where the page stopped matching what you expected.
Inspect traces
A trace is a full debugging recording of a test run, and it gives you a lot more to inspect than a video. Inside one, you get:
- each test step
- DOM snapshots
- screenshots
- console output
- network requests
- errors
- timing
With trace: 'on-first-retry' configured, Playwright records a trace whenever a test fails and retries. You can open a local trace file with:
npx playwright show-trace test-results/path-to-trace.zip
Traces are especially helpful for CI failures. You can’t sit there watching the CI browser, so opening the trace lets you see exactly what it saw. Recording traces takes time and disk space, which is why I only capture them on the first retry instead of keeping one for every passing run. That way I still have full evidence whenever something goes wrong.
Open the HTML report
Playwright generates an HTML report with your test results, and you can open it right from the terminal:
npx playwright show-report
It groups results by browser and test file, along with retries, attachments, errors, screenshots, and traces. Any test that passes only after a retry gets marked as flaky. The retry did its job by gathering evidence, so treat that label as a reminder that the test still has a problem to fix.
Run Playwright in GitHub Actions
To run your suite in GitHub Actions, the runner needs your npm packages, the Playwright browser binaries, and their Linux dependencies. Create .github/workflows/playwright.yml:
name: Playwright tests
on:
push:
branches: [main, master]
pull_request:
branches: [main, master]
jobs:
test:
timeout-minutes: 60
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: lts/*
- name: Install dependencies
run: npm ci
- name: Install Playwright browsers
run: npx playwright install --with-deps
- name: Run Playwright tests
run: npx playwright test
- name: Upload Playwright report
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v7
with:
name: playwright-report
path: playwright-report/
retention-days: 30
When a test fails, the uploaded artifact saves the HTML report so you can download it from the workflow run and open it locally.
Store any login credentials as repository secrets and pass them into the test step instead of putting real credentials in a test file:
- name: Run Playwright tests
run: npx playwright test
env:
TEST_USER_EMAIL: ${{ secrets.TEST_USER_EMAIL }}
TEST_USER_PASSWORD: ${{ secrets.TEST_USER_PASSWORD }}
Keep E2E tests reliable
E2E tests have a reputation for being flaky, and most flaky tests have a concrete cause behind them. These are the rules I follow to keep my suites steady.
Test behavior you control
Keep your tests focused on your own app. Avoid testing third-party pages, analytics scripts, payment provider dashboards, or search engines, since they can change without notice or block automated traffic. Mock the boundary, use a sandbox, or stop the test once your app redirects to the right place.
Use resilient locators
Stick to roles, labels, and visible names whenever you can. Long CSS paths, XPath, and selectors tied to your current DOM structure break as soon as the markup shifts.
Wait for outcomes
Use web-first assertions instead of waitForTimeout() and arbitrary sleeps.
Keep tests independent
Have each test create the data it needs on its own. When tests run in parallel, they shouldn’t depend on execution order or share mutable accounts.
Keep each test focused
A single test that covers signup, profile editing, checkout, cancellation, and logout is hard to debug when it fails. Break it down into user behaviors: keep one complete happy path, then add smaller, focused tests for the important branches.
Control dynamic data
Dates, random recommendations, ads, and live API responses make assertions unstable. Freeze, seed, or mock them whenever they aren’t what the test is checking.
Do not hide failures with retries
Retries are useful in CI because they collect traces and surface flaky tests, though passing on a retry still means something is off. If a test fails once and passes the second time, dig in and find out why.
Decide what to test
Don’t reproduce every unit test in the browser. E2E tests are slower and more expensive to run, so save them for the flows that would hurt if they broke:
- signup and login
- checkout and payments
- creating and saving important data
- permissions and protected pages
- navigation between key pages
- forms with frontend and backend validation
Keep small functions and edge cases in fast unit tests (Vitest is a solid option for JavaScript and TypeScript projects), and use Playwright to make sure all the pieces work together. You’ll get much more value from a small suite covering your critical paths than from hundreds of tests nobody trusts.
A useful test folder structure
Start with a simple layout and don’t build a large abstraction layer on day one:
tests/
auth.setup.ts
homepage.spec.ts
login.spec.ts
cart.spec.ts
checkout.spec.ts
files/
avatar.png
Once repeated actions start getting noisy, pull them out into a small helper:
import type { Page } from '@playwright/test'
async function addBookToCart(page: Page, title: string) {
const book = page
.getByRole('article')
.filter({ hasText: title })
await book.getByRole('button', { name: 'Add to cart' }).click()
}
If a page has many repeated interactions, you can add a page object to cut down the repetition. Just keep the assertions in the tests themselves so the user flow and expected behavior stay easy to read.
Update Playwright
The Playwright npm package and its browser binaries are versioned together. Start by updating the package:
npm install -D @playwright/test@latest
Then install the matching browsers:
npx playwright install --with-deps
You can check the installed version with:
npx playwright --version
If CI suddenly can’t launch a browser after a package update, make sure the CI browser binaries were updated too.
Where to go from here
Don’t start by trying to automate your entire app. Pick one critical flow, install Playwright, configure your local server, and write a test using role and label locators. Run it in UI Mode until it feels solid, then add it to CI. From there, add new tests when a flow matters, when a bug escapes, or when you’re nervous about changing something.
Playwright is useful outside test suites too. You can automate screenshots, data collection, and even record repeatable product demos. A coding agent on a Mac can drive the same browsers, and I wrote about which macOS browsers work for that. For a remote browser that isn’t on your machine, check out TinyFish.
Want me to talk about your product? You can sponsor this site.
Related posts about node: