Playwright Parallel Execution: Workers, fullyParallel and Sharding

Playwright runs tests in parallel for free, and with sharding you can split a suite across many machines. In this lesson you will learn how workers run tests, how to tune parallelism, how to write tests that are safe in parallel and how to shard and merge results.

📖 What You’ll Learn: how workers execute tests, configuring workers, fullyParallel and parallel mode, serial mode, parallel-safe test data, worker index and worker-scoped fixtures, sharding with blob reports, and a speed checklist.


⚡ Why Parallel Execution?

A suite of 300 UI tests at 10 seconds each takes 50 minutes in sequence. With 8 parallel workers it takes about 7 minutes, and split across 4 CI machines about 2 minutes. Fast feedback is what makes automation useful, and Playwright runs tests in parallel out of the box, for free.


👷 How Playwright Runs Tests in Parallel

Playwright starts several worker processes. Each worker is an independent OS process with its own browser.

  • By default, test files run in parallel across workers.
  • Tests inside one file run in order in the same worker.
  • Every test gets a fresh, isolated browser context, so tests do not share cookies or storage.
  • If a test fails, its worker is shut down and a new one starts for the remaining tests.
Running 40 tests using 4 workers
  worker 0: login.spec.ts     (5 tests in order)
  worker 1: cart.spec.ts      (8 tests in order)
  worker 2: checkout.spec.ts  (6 tests in order)
  worker 3: search.spec.ts    ...

🔢 Control the Number of Workers

// playwright.config.ts
export default defineConfig({
  workers: process.env.CI ? 2 : undefined,  // undefined = about half of the CPU cores
});
npx playwright test --workers=4
npx playwright test --workers=50%     # half of the CPU cores
npx playwright test --workers=1       # no parallelism (debugging)

💡 Tip: More workers is not always faster. Each worker runs a browser, which needs CPU and memory. On a 2-core CI runner, 2 workers is usually the sweet spot; measure before increasing.


🧵 Run Tests Inside a File in Parallel

To parallelize individual tests, not only files:

// Whole project
export default defineConfig({
  fullyParallel: true,
});
// One file only
import { test } from '@playwright/test';
test.describe.configure({ mode: 'parallel' });

test('search by name', async ({ page }) => { /* ... */ });
test('search by category', async ({ page }) => { /* ... */ });

With fullyParallel: true the workload is spread more evenly, especially when files have very different sizes.

Opting out: serial tests

Some flows must run in order (for example a multi-step wizard that shares state). Mark them serial; if one fails, the rest are skipped:

test.describe.configure({ mode: 'serial' });

Use serial mode sparingly: independent tests are faster and easier to debug (tags and grouping).


🧪 Write Tests That Are Safe to Run in Parallel

Parallel runs expose hidden dependencies. Follow these rules:

ProblemExampleSolution
Shared test dataTwo tests edit the same user profileCreate unique data per test
Shared account stateTests add and remove items in the same cartOne account per worker, or reset state per test
Order dependenceTest B expects test A’s order to existEach test creates what it needs (via API)
Global limitsThird-party sandbox allows one sessionMock it or run those tests serially

Use the worker index to give each worker its own data:

test('create a project', async ({ page }, testInfo) => {
  const name = 'Project-w' + testInfo.workerIndex + '-' + Date.now();
  // ...create and assert the project with a name no other worker uses
});

For per-worker accounts, a worker-scoped fixture creates one account per worker and reuses it for all its tests (custom fixtures):

import { test as base } from '@playwright/test';

export const test = base.extend<{}, { account: { username: string; password: string } }>({
  account: [async ({}, use, workerInfo) => {
    const username = 'qa_user_' + workerInfo.workerIndex;  // e.g. qa_user_0, qa_user_1 ...
    // create or reset this user via API here
    await use({ username, password: process.env.QA_PASSWORD ?? '' });
  }, { scope: 'worker' }],
});

🧩 Sharding: Split the Suite Across Machines

Sharding divides the tests into N parts and runs each part on a different machine (or CI job):

npx playwright test --shard=1/4
npx playwright test --shard=2/4
npx playwright test --shard=3/4
npx playwright test --shard=4/4

Each shard can still use several workers. Combine shards with the blob reporter and merge the results into one HTML report:

npx playwright test --shard=1/4 --reporter=blob
# ...after all shards...
npx playwright merge-reports --reporter html ./all-blob-reports

📝 Note: Enable fullyParallel: true when sharding, so tests (not whole files) are distributed and shards finish at similar times.

The complete GitHub Actions matrix setup is in Run Playwright tests in GitHub Actions, and merging is explained in reporters.


📏 Speed Checklist

  • Use fullyParallel: true for independent tests.
  • Log in once with a setup project and storageState (save login session) instead of logging in through the UI in every test.
  • Create test data through the API, not the UI (API testing).
  • Block heavy third-party resources in functional tests (network mocking).
  • Run the full browser matrix nightly, and Chromium only on pull requests (cross-browser).
  • Stop early on CI disasters with maxFailures: 10.

📝 Assignment

  1. Run your suite with --workers=1 and then --workers=4, and compare the total time.
  2. Enable fullyParallel: true and observe how tests from the same file now run in different workers (use --reporter=list).
  3. Log testInfo.workerIndex and testInfo.parallelIndex in a test and run with 3 workers.
  4. Make one file serial with test.describe.configure({ mode: 'serial' }), fail its first test on purpose, and observe the skipped tests.
  5. Run the suite as three shards in three terminals with --reporter=blob, then merge the reports.
  6. Bonus: create a worker-scoped fixture that returns a different username per worker.

❓ FAQ

🤔 Does Playwright run tests in parallel by default?

Yes. Test files run in parallel across worker processes. Tests inside a file run in order unless you set fullyParallel: true or mode: 'parallel'.

🤔 How do I set the number of workers in Playwright?

Use workers in the config (a number or a percentage such as '50%') or --workers=N on the command line.

🤔 How do I run Playwright tests sequentially?

Use --workers=1 for the whole run, or test.describe.configure({ mode: 'serial' }) for tests that must run in order.

🤔 What is sharding in Playwright?

Splitting the suite into parts with --shard=x/y so each part runs on a different machine, then merging the blob reports into one report.

🤔 Why do my tests fail only when run in parallel?

They share data or state, such as the same user, cart or record. Give each test or worker its own data, and avoid dependencies between tests.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright Reporters and the HTML Report: Complete Guide

Test results are only useful if people can read them. In this lesson you will configure Playwright’s built-in reporters, get the most from the HTML report, produce JUnit and JSON for CI tools, merge sharded reports and write your own reporter.

📖 What You’ll Learn: what reporters do, every built-in reporter, configuring several reporters, local vs CI setups, the HTML report features, tags, annotations and attachments, merging blob reports from shards, third-party reporters, and writing a custom reporter.


📊 What Is a Reporter?

A reporter decides how Playwright presents test results: lines in the terminal, an interactive HTML page, a JUnit XML file for Jenkins, or a JSON file for your own dashboard. You can use several reporters at once, for example readable terminal output plus an HTML report plus JUnit XML for CI.


🧰 Built-in Reporters

ReporterOutputBest for
listOne line per test with status and timeLocal runs (default when no reporter is set)
lineA single updating line, failures printed in fullLarge suites in a terminal
dotOne character per testCI logs (default on CI when no reporter is set)
htmlInteractive web report in playwright-report/Humans: debugging, sharing results
jsonFull results as JSONDashboards, custom tooling
junitJUnit XMLJenkins, Azure DevOps, GitLab test tabs
githubAnnotations on the failing lines in GitHubGitHub Actions
blobRaw results for mergingSharded runs across machines

Choose one on the command line:

npx playwright test --reporter=list
npx playwright test --reporter=dot
npx playwright test --reporter=line,html

⚙️ Configure Reporters in playwright.config.ts

import { defineConfig } from '@playwright/test';

export default defineConfig({
  reporter: [
    ['list'],                                                    // terminal
    ['html', { outputFolder: 'playwright-report', open: 'never' }], // HTML report
    ['junit', { outputFile: 'results/junit.xml' }],              // for CI test tabs
    ['json', { outputFile: 'results/results.json' }],            // for dashboards
  ],
});

A common pattern is different reporters locally and in CI:

reporter: process.env.CI
  ? [['dot'], ['github'], ['html', { open: 'never' }], ['junit', { outputFile: 'results/junit.xml' }]]
  : [['list'], ['html', { open: 'on-failure' }]],

The HTML open option accepts 'always', 'never' or 'on-failure' (the default opens the report automatically only when tests fail locally).


🌐 The HTML Report in Depth

npx playwright show-report                       # open the last report
npx playwright show-report my-report-folder      # open a report from another folder
npx playwright show-report --port 9323           # choose the port

What you get:

  • Summary of passed, failed, flaky and skipped tests, with filters and search.
  • Results grouped by file and project (browser).
  • Tags and annotations shown on each test (tags, annotations).
  • Every step, including test.step groups, hooks and fixtures, with durations.
  • Errors with code snippets, screenshots, videos and traces (screenshots and videos, Trace Viewer).
  • Attachments you added with testInfo.attach().

The report is a static website. You can zip it, upload it as a CI artifact, or publish it to any static hosting so the whole team can open it in a browser.

Add useful information to the report

test('checkout', {
  tag: '@smoke',
  annotation: { type: 'issue', description: 'https://jira.example.com/browse/QA-42' },
}, async ({ page }, testInfo) => {
  await test.step('open the cart', async () => {
    // ...
  });
  await testInfo.attach('order-details', { body: JSON.stringify({ orderId: 123 }), contentType: 'application/json' });
});

🧩 Merge Reports from Sharded Runs

When you split a suite across several CI machines with --shard, each machine produces a blob report. Merge them into one HTML report:

# on each machine
npx playwright test --shard=1/3 --reporter=blob
# after all shards finish, with all blob-report folders copied into one folder
npx playwright merge-reports --reporter html ./all-blob-reports

The full CI setup is in parallel execution and sharding and GitHub Actions.


🧑‍🔧 Third-Party Reporters

The community offers many reporters. The most popular in QA teams is Allure, with history, trends and categories; see Allure report integration. Others integrate with test management tools and dashboards. Install them from npm and add them to the reporter array like built-in ones.


✍️ Write Your Own Reporter

A custom reporter is a class with optional hooks. This one prints a short summary and the slowest tests:

// reporters/summary-reporter.ts
import type { Reporter, FullConfig, Suite, TestCase, TestResult, FullResult } from '@playwright/test/reporter';

class SummaryReporter implements Reporter {
  private durations: { title: string; ms: number }[] = [];

  onBegin(config: FullConfig, suite: Suite) {
    console.log('Starting ' + suite.allTests().length + ' tests');
  }

  onTestEnd(test: TestCase, result: TestResult) {
    this.durations.push({ title: test.title, ms: result.duration });
    if (result.status === 'failed') console.log('FAILED: ' + test.title);
  }

  onEnd(result: FullResult) {
    const slowest = [...this.durations].sort((a, b) => b.ms - a.ms).slice(0, 3);
    console.log('Finished with status: ' + result.status);
    slowest.forEach(t => console.log('  slow: ' + t.title + ' (' + t.ms + ' ms)'));
  }
}

export default SummaryReporter;
// playwright.config.ts
reporter: [['list'], ['./reporters/summary-reporter.ts']],

Custom reporters are useful for sending results to Slack or Teams, updating a test management tool, or enforcing rules such as “fail the build if any test took longer than 60 seconds”.


✅ Reporting Best Practices

  • Locally: list plus html that opens on failure.
  • In CI: a compact terminal reporter (dot or line), html uploaded as an artifact, junit for the CI test tab, and github annotations on GitHub.
  • Keep reports out of Git (playwright-report/ and test-results/ are already in the default .gitignore).
  • Use tags, annotations and test.step so reports explain themselves.
  • Attach screenshots, videos and traces only for failures to keep reports small.

📝 Assignment

  1. Run your suite with --reporter=list, --reporter=line and --reporter=dot and compare the output.
  2. Configure list, html (open: 'on-failure') and junit together, run the suite, and find all three outputs.
  3. Add a tag, an issue annotation, two test.step blocks and a JSON attachment to one test, then view it in the HTML report.
  4. Add the JSON reporter and read the number of passed tests from the file with a small Node script.
  5. Write the SummaryReporter above, register it, and print the three slowest tests.
  6. Bonus: run the suite as two shards with --reporter=blob and merge them into one HTML report.

❓ FAQ

🤔 How do I generate an HTML report in Playwright?

Add reporter: 'html' (or ['html', { open: 'never' }]) in the config and run the tests. Open it with npx playwright show-report.

🤔 How do I use multiple reporters in Playwright?

Pass an array: reporter: [['list'], ['html'], ['junit', { outputFile: 'results.xml' }]].

🤔 How do I get JUnit XML results for Jenkins?

Add ['junit', { outputFile: 'results/junit.xml' }] to the reporters and point Jenkins’ JUnit plugin at that file. See Playwright with Jenkins.

🤔 How do I merge Playwright reports from shards?

Run each shard with --reporter=blob, collect the blob-report folders, then run npx playwright merge-reports --reporter html <folder>.

🤔 Can I create a custom reporter in Playwright?

Yes. Implement the Reporter interface from @playwright/test/reporter (onBegin, onTestEnd, onEnd and more) and add the file path to the reporter array.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright Trace Viewer Step by Step: Record, Open and Debug Traces

The Trace Viewer turns a mysterious CI failure into a step-by-step replay you can inspect like DevTools. In this lesson you will configure tracing, open traces in several ways, learn every panel of the viewer and follow a real debugging walkthrough.

📖 What You’ll Learn: what a trace contains, trace configuration values, opening traces from the report, CLI and trace.playwright.dev, every Trace Viewer panel, a CI debugging walkthrough, test.step, tracing in plain scripts, and handling traces in CI safely.


🕵️ What Is a Playwright Trace?

A trace is a complete recording of a test run that you can open after the fact. Unlike a video, it is interactive: for every action you can see the DOM before and after, the exact element that was targeted, network requests, console messages and the source line that ran.

That makes the Trace Viewer the best tool for the hardest failures: the ones that only happen in CI, at night, on someone else’s machine. Instead of guessing, you replay the run step by step.


⚙️ Turn On Tracing

Configure tracing once in playwright.config.ts:

import { defineConfig } from '@playwright/test';

export default defineConfig({
  retries: process.env.CI ? 2 : 0,
  use: {
    trace: 'on-first-retry',
  },
});
ValueWhen a trace is recorded or kept
'off'Never (default)
'on'For every test (heavy, use for debugging sessions)
'retain-on-failure'Recorded for every test, kept only for failures
'on-first-retry'Only on the first retry of a failed test (recommended with retries in CI)
'on-all-retries'On every retry
'retain-on-first-failure'Kept only for the first failed attempt

💡 Tip: Use 'on-first-retry' in CI when retries are enabled, or 'retain-on-failure' when they are not. Both give you a trace for every failure without slowing down passing tests much.

Force tracing for one run from the command line:

npx playwright test tests/cart.spec.ts --trace on

📂 Open a Trace

Traces are saved as trace.zip files inside test-results/. Open them in any of these ways:

  1. From the HTML report: run npx playwright show-report, open the failed test, and click the trace image or link.
  2. From the command line: npx playwright show-trace test-results/<test-folder>/trace.zip
  3. In the browser: drag the zip onto trace.playwright.dev. The viewer runs entirely in your browser; the file is not uploaded to a server.
  4. In UI mode (--ui) and the VS Code extension (enable Show trace viewer), traces open automatically.

🧭 Tour of the Trace Viewer

AreaWhat it showsHow it helps
Actions (left)Every Playwright action and assertion, with durationFind the failing step and slow steps
Timeline (top)Filmstrip of screenshots over timeSee what the user would have seen
Snapshots (centre)DOM snapshots: Before, Action, AfterInspect the real page at that moment
Locator pickerPick or type a locator against the snapshotFix locators against the exact failing DOM
CallParameters, locator and timing of the actionCheck what Playwright actually did
LogActionability checks for the actionSee “waiting for element to be visible” and similar
ErrorsError messages and stackJump to the failure
ConsoleBrowser console logs and page errorsSpot JavaScript errors in the app
NetworkEvery request with status, timing, headers and bodyFind failed or slow API calls
SourceYour test code, with the current line highlightedConnect the step to your code
AttachmentsScreenshots and files attached in the testExtra evidence

Reading the “Action” snapshot

Click a click-step and choose the Action tab: a red dot shows exactly where Playwright clicked. If the dot is on an overlay or the wrong element, you have found the bug.


🧪 A Debugging Walkthrough

Imagine this test fails only in CI with “Timeout 30000ms exceeded” on click():

test('checkout', async ({ page }) => {
  // ...log in, add item...
  await page.getByRole('button', { name: 'Checkout' }).click();
});

In the trace:

  1. Actions: the click step is red and took 30 seconds.
  2. Log: the element is visible, enabled and stable, followed by repeated “another element would receive the click”.
  3. Snapshot (Before): a cookie consent banner covers the bottom of the page in the CI viewport.
  4. Network: the banner script loaded only in CI because a feature flag differed.

Fix: accept or close the banner in a beforeEach (or set the consent cookie), and align the viewport with production. No guessing, no “works on my machine”.


🏷️ Make Traces Easier to Read with test.step

Group actions into named steps; they appear as collapsible sections in the trace and the HTML report:

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

test('purchase a backpack', async ({ page }) => {
  await test.step('log in', async () => {
    await page.goto('https://www.saucedemo.com/');
    await page.getByPlaceholder('Username').fill('standard_user');
    await page.getByPlaceholder('Password').fill('secret_sauce');
    await page.getByRole('button', { name: 'Login' }).click();
  });

  await test.step('add backpack to cart', async () => {
    await page.locator('[data-test="add-to-cart-sauce-labs-backpack"]').click();
    await expect(page.locator('.shopping_cart_badge')).toHaveText('1');
  });
});

🛠️ Record Traces Outside the Test Runner

In plain Playwright library scripts, start and stop tracing on the context:

import { chromium } from 'playwright';

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  await context.tracing.start({ screenshots: true, snapshots: true, sources: true });

  const page = await context.newPage();
  await page.goto('https://www.saucedemo.com/');

  await context.tracing.stop({ path: 'trace.zip' });
  await browser.close();
})();

☁️ Traces in CI

To use traces from CI runs, upload the report folder as a build artifact (shown in full in the GitHub Actions and Jenkins lessons):

- uses: actions/upload-artifact@v4
  if: ${{ !cancelled() }}
  with:
    name: playwright-report
    path: playwright-report/
    retention-days: 14

Download the artifact, open the HTML report, and click the trace of the failed test.

⚠️ Common mistake: Traces contain everything the page saw, including cookies, tokens and form values. Treat trace files like logs with sensitive data: limit who can download CI artifacts and use test accounts only.


📝 Assignment

  1. Set trace: 'retain-on-failure', break one Sauce Demo test, and open its trace from the HTML report.
  2. In the trace, find the failing action, read its Log, and inspect the Before and After snapshots.
  3. Use the locator picker in the trace to find a working locator for the element you broke.
  4. Open the Network tab and list the requests made when the inventory page loaded.
  5. Wrap your test in two or three test.step blocks and see how the trace groups actions.
  6. Open the same trace with npx playwright show-trace and on trace.playwright.dev.
  7. Bonus: record a trace from a plain Node script with context.tracing.start().

❓ FAQ

🤔 What is the Playwright Trace Viewer?

A GUI tool that replays a recorded test run action by action, with DOM snapshots, network requests, console logs and source code, so you can debug failures after they happened.

🤔 How do I open a Playwright trace?

From the HTML report, with npx playwright show-trace path/to/trace.zip, or by dropping the file onto trace.playwright.dev.

🤔 Which trace setting should I use in CI?

'on-first-retry' when retries are enabled, or 'retain-on-failure' otherwise. Both keep traces for failures without recording every passing test permanently.

🤔 Is trace.playwright.dev safe for private traces?

The viewer loads the file locally in your browser and does not upload it. Still follow your company’s policy for handling files that contain sensitive data.

🤔 What is the difference between a trace and a video?

A video only shows pixels. A trace lets you inspect the DOM, locators, network, console and source for every step, which makes root-cause analysis much faster.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Debugging Playwright Tests: Inspector, page.pause, UI Mode and VS Code

Every automation engineer spends time debugging. Playwright makes it fast with excellent error messages, the Inspector, UI mode and VS Code integration. In this lesson you will learn a step-by-step debugging workflow and the right tool for each kind of failure.

📖 What You’ll Learn: reading errors and call logs, the Playwright Inspector with –debug, page.pause, UI mode, VS Code breakpoints, slow motion and headed runs, capturing console and network errors, DEBUG logs, and a symptom-to-tool troubleshooting table.


🐞 A Debugging Mindset

When a Playwright test fails, ask three questions in order:

  1. What did the error say? Playwright errors include the locator, the expected and received values, and a call log of what it tried.
  2. What did the page look like? Use screenshots, UI mode or the trace.
  3. What happened step by step? Step through the test with the Inspector or a breakpoint.

Playwright gives you a tool for each question. This lesson covers all of them; the most powerful one, the Trace Viewer, has its own lesson.


📜 Step 1: Read the Error Message and Call Log

Error: expect(locator).toHaveText(expected) failed

Locator: locator('.title')
Expected string: "Product"
Received string: "Products"
Timeout: 5000ms

Call log:
  - Expect "toHaveText" with timeout 5000ms
  - waiting for locator('.title')
    9 × locator resolved to <span class="title" data-test="title">Products</span>
      - unexpected value "Products"

The call log shows that the element was found nine times and its text was always “Products”. The test, not the app, is wrong. For actions you will see entries such as “element is not visible” or “another element would receive the click”, which point straight at the cause.


🧭 Step 2: Playwright Inspector with –debug

Run a test in debug mode:

npx playwright test tests/login.spec.ts --debug           # debug a file
npx playwright test tests/login.spec.ts:12 --debug        # debug the test on line 12
npx playwright test -g "locked out user" --debug          # debug by title

A headed browser and the Playwright Inspector open, paused before the first action. In the Inspector you can:

ControlWhat it does
Step overRun the next action only
ResumeContinue until the next page.pause() or the end
Pick locatorClick an element to see the best locator for it
Locator boxEdit a locator and see live which elements it highlights
Call logWatch Playwright’s actionability checks for the current step

The element the next action targets is highlighted in the browser, so you immediately see whether the locator points at the right element.

💡 Tip: Use the locator box to fix a broken locator before editing the code: type your new locator and check that exactly one element is highlighted.


⏸️ Step 3: Pause Exactly Where You Need with page.pause()

Add await page.pause() anywhere in a test and run it headed. Execution stops there with the Inspector open:

test('checkout total', async ({ page }) => {
  await page.goto('https://www.saucedemo.com/');
  await page.getByPlaceholder('Username').fill('standard_user');
  await page.getByPlaceholder('Password').fill('secret_sauce');
  await page.getByRole('button', { name: 'Login' }).click();

  await page.pause();   // inspect the products page here

  await page.locator('[data-test="add-to-cart-sauce-labs-backpack"]').click();
});
npx playwright test tests/checkout.spec.ts --headed

Remove page.pause() before committing; with forbidOnly-style discipline, a lint rule such as playwright/no-page-pause catches leftovers.


🖥️ Step 4: UI Mode for Day-to-Day Debugging

npx playwright test --ui

UI mode is the most comfortable way to develop and debug tests:

  • Run any test, file or tag with one click; watch mode re-runs on save.
  • A timeline of every action with before and after DOM snapshots you can inspect like DevTools.
  • Network, console, errors and source tabs for the selected step.
  • Pick locator directly on the snapshot.

Most “why did it click the wrong thing?” questions are answered by clicking the step in the timeline and looking at the highlighted element.


🧑‍💻 Step 5: Debug in VS Code with Breakpoints

With the Playwright Test for VSCode extension:

  1. Click in the gutter next to a line to set a breakpoint.
  2. Right-click the green ▶ next to the test and choose Debug Test.
  3. Execution stops at the breakpoint; hover variables, use the Debug Console, step with F10.
  4. Tick Show browser to watch the page; while paused, editing a locator in the code highlights the matching element in the browser.

This combines normal TypeScript debugging (variables, call stack) with live browser feedback.


🐢 Step 6: Slow Down and Watch

Sometimes you simply need to see what happens:

npx playwright test --headed --workers=1 --project=chromium
// playwright.config.ts: slow every action down by 500 ms (debugging only)
use: {
  launchOptions: { slowMo: 500 },
},

⚠️ Common mistake: Never leave slowMo or headless: false in the shared config; they make CI slow. Put them in a local-only config or pass --headed on the command line.


📢 Step 7: Capture Browser Console and Network Errors

Front-end JavaScript errors often explain UI failures. Print them during the test:

test.beforeEach(async ({ page }) => {
  page.on('console', msg => {
    if (msg.type() === 'error') console.log('Browser console error:', msg.text());
  });
  page.on('pageerror', err => console.log('Uncaught page error:', err.message));
  page.on('requestfailed', req => console.log('Request failed:', req.url(), req.failure()?.errorText));
});

For very detailed Playwright internals, enable debug logs:

# macOS / Linux
DEBUG=pw:api npx playwright test tests/login.spec.ts

# Windows PowerShell
$env:DEBUG='pw:api'; npx playwright test tests/login.spec.ts

🧰 Debugging Toolbox Summary

ToolBest forCommand
Error + call logFirst look at any failureAlways printed
InspectorStepping through actions, fixing locators--debug
page.pause()Stopping at one exact pointAdd to code, run --headed
UI modeDeveloping and exploring tests--ui
VS Code debuggerVariables, logic, breakpointsDebug Test
Trace ViewerFailures in CI, after the facttrace: 'on-first-retry'
Screenshots and videoQuick visual evidencescreenshot, video in config

🔎 Common Failures and Where to Look

SymptomLikely causeDebug with
“strict mode violation”Locator matches several elementsInspector locator box
“element is not visible”Hidden, wrong tab, not yet renderedUI mode snapshot
“intercepts pointer events”Overlay, modal or cookie bannerUI mode snapshot, trace
Assertion timeout with wrong valueTest data or app logicError + call log
Passes locally, fails in CITiming, environment, dataTrace Viewer, flaky tests

📝 Assignment

  1. Break a locator in one of your Sauce Demo tests on purpose, read the error and call log, and write down what they told you.
  2. Run the test with --debug, step through it, and fix the locator using the Inspector’s locator box.
  3. Add page.pause() after login, run headed, and use Pick locator on three elements.
  4. Open UI mode, run your suite, and inspect the before and after snapshots of a click.
  5. Set a breakpoint in VS Code inside a test, run Debug Test, and inspect a variable.
  6. Add console and page-error listeners in a beforeEach and visit a page that logs errors.
  7. Bonus: run one test with DEBUG=pw:api and find the line where Playwright waits for the element to be visible.

❓ FAQ

🤔 How do I debug a Playwright test?

Run it with npx playwright test --debug to open the Inspector, use --ui for UI mode, add await page.pause() to stop at a point, or use Debug Test in VS Code with breakpoints.

🤔 What does page.pause() do in Playwright?

It stops the test and opens the Playwright Inspector so you can explore the page, pick locators and continue step by step. It only works in headed mode.

🤔 How do I run Playwright in slow motion?

Set launchOptions: { slowMo: 500 } in the config (for local debugging only), or use --debug and step through actions.

🤔 How do I see browser console logs in Playwright?

Listen to the console event: page.on('console', msg => console.log(msg.text())), and to pageerror for uncaught exceptions.

🤔 What is the difference between UI mode and the Trace Viewer?

UI mode runs tests interactively on your machine with a live timeline. The Trace Viewer opens recorded traces after a run, which is ideal for failures that happened in CI.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright Framework Folder Structure: Best Practices with TypeScript

A good folder structure is the difference between a framework that scales and one that collapses after 200 tests. In this lesson you will build a proven Playwright + TypeScript framework layout, understand each layer, and apply naming and quality rules used in real teams.

📖 What You’ll Learn: why structure matters, a recommended folder layout, the framework layers and their rules, example page objects, data, fixtures and tests, tsconfig path aliases, environment configuration, naming conventions, code quality tooling and a framework checklist.


🏗️ Why Folder Structure Matters

A Playwright project with 20 tests can live in one folder. A project with 2,000 tests, five contributors and three environments cannot. A clear structure gives you:

  • Findability: anyone can guess where a page object, a fixture or a data file lives.
  • Reuse: login, API clients and helpers are written once.
  • Safe change: a UI change is fixed in one page object, not in 40 tests.
  • Easy onboarding: new team members follow existing patterns.

This lesson presents a proven structure for Playwright + TypeScript frameworks, explains every folder, and shows how the layers connect.


📁 Recommended Folder Structure

playwright-framework/
├── .github/workflows/
│   └── playwright.yml          # CI pipeline
├── config/
│   ├── env.ts                  # reads and validates environment variables
│   └── environments.ts         # URLs per environment (dev, qa, staging)
├── src/
│   ├── pages/                  # Page Object Model
│   │   ├── BasePage.ts
│   │   ├── LoginPage.ts
│   │   ├── InventoryPage.ts
│   │   └── components/
│   │       └── HeaderComponent.ts
│   ├── api/                    # API clients for setup and API tests
│   │   ├── ApiClient.ts
│   │   └── UsersApi.ts
│   ├── fixtures/
│   │   └── index.ts            # custom test with pages, API clients, test data
│   ├── data/                   # static test data
│   │   ├── users.ts
│   │   └── products.json
│   ├── utils/                  # pure helpers (dates, random data, formatting)
│   │   └── random.ts
│   └── types/                  # shared interfaces
│       └── user.ts
├── tests/
│   ├── auth.setup.ts           # logs in once, saves storageState
│   ├── ui/
│   │   ├── login.spec.ts
│   │   └── cart.spec.ts
│   ├── api/
│   │   └── users.api.spec.ts
│   └── visual/
│       └── home.visual.spec.ts
├── playwright/.auth/           # saved sessions (git-ignored)
├── .env.example                # documented variables, no secrets
├── .gitignore
├── eslint.config.mjs
├── package.json
├── playwright.config.ts
└── tsconfig.json

💡 Tip: Keep framework code (src/) separate from tests (tests/). Tests should read like user stories; all the “how” lives in src/.


🧱 The Layers and How They Connect

Each layer only talks to the layer below it:

LayerFolderResponsibilityKnows about
Teststests/What to verify, written as user flowsFixtures
Fixturessrc/fixtures/Create and inject page objects, API clients, dataPages, API, data
Pages and componentssrc/pages/Locators and user actions for one page or widgetPlaywright Page
API clientssrc/api/HTTP calls for setup, cleanup and API testsPlaywright APIRequestContext
Data, types, utilssrc/data/, src/types/, src/utils/Static data, interfaces, pure helpersNothing above
Configconfig/, playwright.config.tsEnvironments, browsers, timeouts, reportersEnvironment variables

Rules that keep the framework clean:

  1. Tests never contain raw selectors; they call page-object methods.
  2. Page objects never contain assertions about business rules; tests do (simple “is the page loaded” checks are fine).
  3. Utilities are pure functions with no Playwright dependency.
  4. Secrets come only from environment variables.

📄 Example Files

src/pages/BasePage.ts

import { Page } from '@playwright/test';

export abstract class BasePage {
  constructor(protected readonly page: Page) {}
  protected abstract readonly path: string;

  async open(): Promise<void> {
    await this.page.goto(this.path);
  }
}

src/pages/LoginPage.ts

import { Page, Locator } from '@playwright/test';
import { BasePage } from './BasePage';

export class LoginPage extends BasePage {
  protected readonly path = '/';
  readonly username: Locator;
  readonly password: Locator;
  readonly submit: Locator;
  readonly error: Locator;

  constructor(page: Page) {
    super(page);
    this.username = page.getByPlaceholder('Username');
    this.password = page.getByPlaceholder('Password');
    this.submit = page.getByRole('button', { name: 'Login' });
    this.error = page.locator('[data-test="error"]');
  }

  async login(user: { username: string; password: string }): Promise<void> {
    await this.username.fill(user.username);
    await this.password.fill(user.password);
    await this.submit.click();
  }
}

src/types/user.ts and src/data/users.ts

// src/types/user.ts
export interface User { username: string; password: string }

// src/data/users.ts
import { User } from '../types/user';

export const users = {
  standard: { username: 'standard_user', password: process.env.SAUCE_PASSWORD ?? 'secret_sauce' },
  locked:   { username: 'locked_out_user', password: process.env.SAUCE_PASSWORD ?? 'secret_sauce' },
} satisfies Record<string, User>;

src/fixtures/index.ts

import { test as base } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';
import { InventoryPage } from '../pages/InventoryPage';

type Fixtures = {
  loginPage: LoginPage;
  inventoryPage: InventoryPage;
};

export const test = base.extend<Fixtures>({
  loginPage: async ({ page }, use) => { await use(new LoginPage(page)); },
  inventoryPage: async ({ page }, use) => { await use(new InventoryPage(page)); },
});
export { expect } from '@playwright/test';

tests/ui/login.spec.ts

import { test, expect } from '../../src/fixtures';
import { users } from '../../src/data/users';

test.describe('Login', { tag: '@smoke' }, () => {
  test('standard user reaches the products page', async ({ loginPage, page }) => {
    await loginPage.open();
    await loginPage.login(users.standard);
    await expect(page).toHaveURL(/inventory/);
  });

  test('locked user sees an error', async ({ loginPage }) => {
    await loginPage.open();
    await loginPage.login(users.locked);
    await expect(loginPage.error).toContainText('locked out');
  });
});

The test is short, readable and free of selectors. Learn each building block in depth: Page Object Model, custom fixtures, API with POM.


🔗 Cleaner Imports with Path Aliases

Long relative paths like ../../src/pages/LoginPage are hard to read. Define aliases in tsconfig.json; Playwright resolves them automatically:

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "commonjs",
    "strict": true,
    "baseUrl": ".",
    "paths": {
      "@pages/*": ["src/pages/*"],
      "@fixtures": ["src/fixtures/index.ts"],
      "@data/*": ["src/data/*"]
    }
  }
}
import { test, expect } from '@fixtures';
import { users } from '@data/users';

🌍 Environments and Config

Keep environment-specific values out of the code:

// config/environments.ts
export const environments = {
  dev:     'https://dev.example.com',
  qa:      'https://qa.example.com',
  staging: 'https://staging.example.com',
} as const;

export type EnvName = keyof typeof environments;
// playwright.config.ts (excerpt)
import 'dotenv/config';
import { defineConfig } from '@playwright/test';
import { environments, EnvName } from './config/environments';

const env = (process.env.TEST_ENV ?? 'qa') as EnvName;

export default defineConfig({
  use: { baseURL: environments[env] },
});

Run against another environment with TEST_ENV=staging npx playwright test (on PowerShell: $env:TEST_ENV='staging'; npx playwright test). Details in .env files and multiple config files.


📏 Naming Conventions

ItemConventionExample
UI test filesfeature.spec.tscheckout.spec.ts
API test filesfeature.api.spec.tsusers.api.spec.ts
Setup filesname.setup.tsauth.setup.ts
Page objectsPascalCase + PageCheckoutPage.ts
ComponentsPascalCase + ComponentHeaderComponent.ts
Test titlesBehaviour, not steps'guest can apply a discount code'
Locator propertiesNoun describing the elementsubmitButton, cartBadge
Action methodsVerb describing the user intentlogin(), addToCart()

🧹 Code Quality Tooling

  • ESLint with typescript-eslint and eslint-plugin-playwright (rules such as no-floating-promises and playwright/no-wait-for-timeout).
  • Prettier for consistent formatting.
  • Type check in CI: npx tsc --noEmit (TypeScript for Playwright).
  • Pre-commit hook (Husky + lint-staged) to lint changed files.
  • .env.example listing every variable without real values.

✅ Framework Checklist

  • Tests contain no selectors and no hard-coded URLs or secrets.
  • Every page and reusable widget has one class.
  • Login runs once per run through a setup project with storageState.
  • Test data is typed and lives in src/data or is generated per test.
  • One command runs everything locally the same way CI does.
  • CI uploads the HTML report and traces on failure.

📝 Assignment

  1. Create the folder structure above for Sauce Demo (you can leave some folders empty).
  2. Move your login and cart tests into tests/ui/ and create LoginPage, InventoryPage and BasePage in src/pages/.
  3. Create src/fixtures/index.ts that injects both page objects, and update the tests to use it.
  4. Add path aliases @pages/*, @fixtures and @data/* and replace the relative imports.
  5. Add config/environments.ts and select the base URL with TEST_ENV.
  6. Install ESLint with the Playwright plugin and fix every warning.
  7. Bonus: add an auth.setup.ts setup project that logs in once and saves storageState.

❓ FAQ

🤔 What is the best folder structure for a Playwright framework?

Separate tests (tests/) from framework code (src/ with pages, API clients, fixtures, data, types and utils), keep configuration in config/ and playwright.config.ts, and store sessions and reports in git-ignored folders.

🤔 Where should page objects go in Playwright?

In a dedicated folder such as src/pages/, with one class per page and a components/ subfolder for reusable widgets.

🤔 Should Playwright UI tests and API tests be in separate folders?

Yes. Separate folders (and usually separate projects in the config) make it easy to run them independently and give them different settings.

🤔 Can I use TypeScript path aliases in Playwright?

Yes. Define paths in tsconfig.json; Playwright Test resolves them automatically.

🤔 How do I switch environments in a Playwright framework?

Store URLs per environment in a config file and choose one with an environment variable such as TEST_ENV, read in playwright.config.ts.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

API Testing with Playwright and TypeScript: GET, POST, PUT, PATCH, DELETE

Playwright is not only for browsers: it includes a complete HTTP client for API testing. In this lesson you will test a REST API with GET, POST, PUT, PATCH and DELETE requests, handle authentication, type your responses and combine API calls with UI tests.

📖 What You’ll Learn: why API testing in Playwright, an API project with baseURL, the request fixture, GET with params, POST, PUT, PATCH and DELETE, request options and response methods, authentication with tokens, typed responses, and combining API setup with UI checks.


🔌 Why API Testing with Playwright?

Most applications are a user interface on top of REST APIs. Testing those APIs directly is fast, stable and catches backend bugs early. Playwright includes a full HTTP client, so you can write API tests in the same framework, language and report as your UI tests, with no Postman collection or separate library to maintain.

API tests in Playwright:

  • Run in milliseconds, without opening a browser.
  • Use the same expect assertions, fixtures, tags, retries and HTML report.
  • Can be combined with UI tests, for example to create test data via API before checking it in the browser.

We will use JSONPlaceholder (https://jsonplaceholder.typicode.com), a free fake REST API. It accepts POST, PUT, PATCH and DELETE requests and returns realistic responses, but does not really save changes.


⚙️ Setup: baseURL for API Tests

Set the API address once in playwright.config.ts. A separate project keeps API tests apart from browser tests:

import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  projects: [
    {
      name: 'api',
      testMatch: /.*\.api\.spec\.ts/,
      use: {
        baseURL: 'https://jsonplaceholder.typicode.com',
        extraHTTPHeaders: { Accept: 'application/json' },
      },
    },
    { name: 'chromium', testIgnore: /.*\.api\.spec\.ts/, use: { ...devices['Desktop Chrome'] } },
  ],
});
npx playwright test --project=api

📥 GET: Read Data

The built-in request fixture is an APIRequestContext. Relative URLs use the baseURL:

// tests/posts.api.spec.ts
import { test, expect } from '@playwright/test';

test('GET a single post', async ({ request }) => {
  const response = await request.get('/posts/1');

  expect(response.status()).toBe(200);
  await expect(response).toBeOK();               // any 2xx status

  const post = await response.json();
  expect(post).toMatchObject({ id: 1, userId: 1 });
  expect(typeof post.title).toBe('string');
});

test('GET with query parameters', async ({ request }) => {
  const response = await request.get('/posts', { params: { userId: 1 } });
  await expect(response).toBeOK();

  const posts = await response.json();
  expect(posts).toHaveLength(10);
  for (const p of posts) {
    expect(p.userId).toBe(1);
  }
});

📤 POST: Create Data

test('POST creates a post', async ({ request }) => {
  const newPost = { title: 'Learn Playwright API testing', body: 'It is fast!', userId: 1 };

  const response = await request.post('/posts', { data: newPost });

  expect(response.status()).toBe(201);
  const created = await response.json();
  expect(created).toMatchObject(newPost);
  expect(created.id).toEqual(expect.any(Number));
});

data is sent as JSON automatically when you pass an object. For HTML forms use form: { ... }, and for file uploads use multipart: { ... }.


✏️ PUT and PATCH: Update Data

test('PUT replaces a post', async ({ request }) => {
  const response = await request.put('/posts/1', {
    data: { id: 1, title: 'Updated title', body: 'Updated body', userId: 1 },
  });
  await expect(response).toBeOK();
  expect((await response.json()).title).toBe('Updated title');
});

test('PATCH updates one field', async ({ request }) => {
  const response = await request.patch('/posts/1', { data: { title: 'Only the title changed' } });
  await expect(response).toBeOK();
  expect((await response.json()).title).toBe('Only the title changed');
});

PUT replaces the whole resource; PATCH changes only the fields you send.


🗑️ DELETE: Remove Data

test('DELETE removes a post', async ({ request }) => {
  const response = await request.delete('/posts/1');
  expect(response.status()).toBe(200);
});

🧰 Request Options and Response Methods

Request optionPurpose
paramsQuery string, e.g. { userId: 1 }
dataJSON body (object) or raw string
formURL-encoded form body
multipartMultipart body with files
headersExtra headers for this request
timeoutRequest timeout in ms
failOnStatusCodeThrow automatically if the status is not 2xx or 3xx
Response methodReturns
status()Status code, e.g. 200
ok()true for 200 to 299
json()Parsed JSON body
text()Body as a string
headers()Response headers as an object
body()Raw body as a Buffer

🔐 Authentication: Tokens and Headers

Real APIs need authentication. Keep secrets in environment variables (.env files) and send them as headers:

// For every request in the project
use: {
  baseURL: process.env.API_URL,
  extraHTTPHeaders: { Authorization: 'Bearer ' + process.env.API_TOKEN },
},

Or log in once and create an authenticated context yourself:

import { test, expect, request as playwrightRequest, APIRequestContext } from '@playwright/test';

let api: APIRequestContext;

test.beforeAll(async () => {
  const auth = await playwrightRequest.newContext({ baseURL: process.env.API_URL });
  const login = await auth.post('/auth/login', { data: { username: process.env.API_USER, password: process.env.API_PASSWORD } });
  const { token } = await login.json();

  api = await playwrightRequest.newContext({
    baseURL: process.env.API_URL,
    extraHTTPHeaders: { Authorization: 'Bearer ' + token },
  });
});

test.afterAll(async () => {
  await api.dispose();
});

test('get my profile', async () => {
  const response = await api.get('/me');
  await expect(response).toBeOK();
});

🧾 Type Your API Responses

Give responses a TypeScript type so your editor autocompletes fields and catches typos (interfaces, generics):

interface Post { userId: number; id: number; title: string; body: string }

test('typed response', async ({ request }) => {
  const post: Post = await (await request.get('/posts/1')).json();
  expect(post.title.length).toBeGreaterThan(0);
});

Types do not validate data at runtime. For strict contract checks, combine toMatchObject and expect.any(Number) as above, or add a JSON-schema library.


🔗 Combine API and UI Tests

The real power: use the API for setup and the browser for verification. page.request shares cookies with the browser page, so it acts as the logged-in user:

test('order created via API appears in the UI', async ({ page }) => {
  await page.goto('https://your-app.example.com/login');
  // ...log in through the UI or reuse a saved session...

  const response = await page.request.post('/api/orders', { data: { product: 'Backpack', qty: 1 } });
  await expect(response).toBeOK();
  const order = await response.json();

  await page.goto('/orders');
  await expect(page.getByText('Order #' + order.id)).toBeVisible();
});

This is faster and more reliable than creating the order by clicking through five screens. Organizing API calls in classes is covered in API automation with Page Object Model.


📝 Assignment

Use https://jsonplaceholder.typicode.com:

  1. Create an api project with baseURL and a *.api.spec.ts file.
  2. GET /users/1 and assert the user has id: 1 and a string email.
  3. GET /comments with params: { postId: 1 } and assert every comment has postId 1.
  4. POST a new todo to /todos and assert status 201 and the returned title.
  5. PATCH /todos/1 to completed: true and assert the response.
  6. DELETE /todos/1 and assert status 200.
  7. Bonus: write an interface for Todo and a generic helper getJson<T>(request, url) that returns typed data.

❓ FAQ

🤔 Can Playwright be used for API testing?

Yes. The built-in request fixture (APIRequestContext) sends GET, POST, PUT, PATCH and DELETE requests, and you assert responses with the same expect as UI tests.

🤔 How do I send a POST request in Playwright?

await request.post('/posts', { data: { title: 'x' } }). Passing an object as data sends it as JSON.

🤔 How do I add an authorization header in Playwright API tests?

Set extraHTTPHeaders: { Authorization: 'Bearer ' + token } in the config or in request.newContext(), or pass headers on a single request.

🤔 Do Playwright API tests need a browser?

No. The request fixture sends HTTP requests directly, so API tests run without launching a browser.

🤔 Is Playwright a replacement for Postman?

For automated API tests in CI, yes: tests live in code, run with your UI suite and share one report. Postman remains handy for manual exploration.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Network Interception and API Mocking in Playwright (page.route)

With network interception, Playwright can fake API responses, simulate server errors, block ads and record traffic. In this lesson you will learn page.route step by step with examples on Playwright’s official API-mocking demo page.

📖 What You’ll Learn: what network interception is, page.route patterns, mocking responses with fulfill, modifying real responses with route.fetch, simulating errors and slow APIs, changing requests, blocking resources, request and response events, context.route, HAR record and replay, and when to mock.


🛰️ What Is Network Interception?

Every modern web page talks to a backend through network requests: fetching products, submitting forms, loading images. Playwright can sit between the browser and the network and:

  • Observe requests and responses (what was called, with which data).
  • Mock responses: return your own data instead of calling the real server.
  • Modify real responses before the page sees them.
  • Block requests you do not need, such as ads, analytics or large images.

This lets you test situations that are hard to create for real: empty lists, server errors, slow APIs, or a feature whose backend is not finished yet.


🧭 page.route(): The Core API

await page.route(urlPattern, async route => {
  // decide what to do with each matching request:
  // route.fulfill(...)  → respond with mock data
  // route.continue(...) → send it to the real server (optionally modified)
  // route.abort()       → block it
});

The URL pattern can be a glob ('**/api/products'), a regular expression (/\/api\/v\d\/fruits/) or a function. Register routes before the page makes the request, usually before page.goto().


🍓 Mock an API Response

Playwright’s official demo page https://demo.playwright.dev/api-mocking loads a list of fruits from /api/v1/fruits. Replace the real list with your own:

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

test('shows mocked fruit', async ({ page }) => {
  await page.route('*/**/api/v1/fruits', async route => {
    const json = [{ name: 'Strawberry', id: 21 }];
    await route.fulfill({ json });              // status 200 with a JSON body
  });

  await page.goto('https://demo.playwright.dev/api-mocking');
  await expect(page.getByText('Strawberry')).toBeVisible();
});

route.fulfill() options:

OptionPurpose
jsonBody as an object, sets the JSON content type automatically
statusHTTP status code, e.g. 500
bodyRaw string or Buffer body
contentTypee.g. 'text/html'
headersResponse headers
pathServe the body from a local file

✏️ Modify a Real Response

Fetch the real response, change it, then return it. This keeps the test close to reality while controlling one detail:

test('adds a fruit to the real list', async ({ page }) => {
  await page.route('*/**/api/v1/fruits', async route => {
    const response = await route.fetch();       // real request
    const json = await response.json();
    json.push({ name: 'Loquat', id: 100 });     // add one item
    await route.fulfill({ response, json });    // keep real status and headers
  });

  await page.goto('https://demo.playwright.dev/api-mocking');
  await expect(page.getByText('Loquat', { exact: true })).toBeVisible();
});

💥 Simulate Errors, Empty Data and Slow Responses

Use mocks to test how your application handles problems. Point these at your own app’s endpoints and assert its error or empty states:

// Server error
await page.route('**/api/orders', route => route.fulfill({ status: 500, body: 'Internal Server Error' }));

// Empty list
await page.route('**/api/orders', route => route.fulfill({ json: [] }));

// Network failure
await page.route('**/api/orders', route => route.abort('failed'));

// Slow API: wait 3 seconds before continuing to the real server
await page.route('**/api/orders', async route => {
  await new Promise(resolve => setTimeout(resolve, 3000));
  await route.continue();
});

💡 Tip: Error-state tests are where mocking shines. Ask: what should the user see when the API returns 500, an empty array, or takes 10 seconds? Then write a test for each.


🔧 Modify Outgoing Requests

route.continue() can change the request before it reaches the server:

await page.route('**/api/**', async route => {
  const headers = { ...route.request().headers(), 'x-test-run': 'playwright' };
  await route.continue({ headers });
});

You can also change method, postData or url, for example to point one endpoint at a staging server.


🚫 Block Unneeded Resources

Blocking images, fonts or third-party scripts can make tests faster and more stable:

test.beforeEach(async ({ page }) => {
  await page.route('**/*.{png,jpg,jpeg,gif,svg,webp}', route => route.abort());
  await page.route(/google-analytics|googletagmanager|doubleclick/, route => route.abort());
});

⚠️ Common mistake: Do not block resources in tests that check layout or images. Blocking is for functional tests where those resources do not matter.


👂 Listen to Requests and Responses

To observe traffic without changing it, use events:

page.on('request', request => console.log('>>', request.method(), request.url()));
page.on('response', response => console.log('<<', response.status(), response.url()));
page.on('requestfailed', request => console.log('FAILED', request.url(), request.failure()?.errorText));

To wait for one specific call and assert its data, use page.waitForResponse(), explained in Playwright waits:

const responsePromise = page.waitForResponse('**/api/v1/fruits');
await page.goto('https://demo.playwright.dev/api-mocking');
const response = await responsePromise;
expect(response.status()).toBe(200);

🌍 Routes for All Pages: context.route()

page.route() applies to one tab. context.route() applies to every page in the browser context, including popups and new tabs:

test('mock for every tab', async ({ context, page }) => {
  await context.route('**/api/config', route => route.fulfill({ json: { featureX: true } }));
  await page.goto('https://example.com');
});

Remove a route with page.unroute(pattern) or page.unrouteAll().


📼 Record and Replay with HAR Files

A HAR file is a recording of network traffic. Record real responses once, then replay them in tests so they do not depend on the backend:

// First run: record (update: true) the API traffic into a HAR file
await page.routeFromHAR('./hars/fruits.har', { url: '*/**/api/v1/fruits', update: true });
await page.goto('https://demo.playwright.dev/api-mocking');

// Later runs: remove update: true to replay the saved responses
// await page.routeFromHAR('./hars/fruits.har', { url: '*/**/api/v1/fruits' });

⚖️ When to Mock (and When Not To)

Mock itUse the real backend
Error, empty and edge-case statesCritical end-to-end business flows
Third-party services (payments, maps, SMS)Smoke tests before a release
Features whose backend is not readyContract between frontend and backend
Slow or rate-limited APIsData that must really be saved

A healthy suite has both: a few full end-to-end tests against real services, and many focused tests that mock the network.


📝 Assignment

Use https://demo.playwright.dev/api-mocking:

  1. Mock /api/v1/fruits to return three fruits of your choice and assert all three are visible.
  2. Modify the real response by adding a fruit with route.fetch() and assert it appears.
  3. Mock an empty array and describe what the page shows.
  4. Log every request and response URL while the page loads.
  5. Use page.waitForResponse to assert the fruits API returns status 200.
  6. On https://www.saucedemo.com block all images with route.abort() and log in; confirm the test still passes.
  7. Bonus: record the fruits API into a HAR file and replay it in a second test.

❓ FAQ

🤔 How do I mock an API response in Playwright?

Register a route before navigation and fulfill it: await page.route('**/api/items', route => route.fulfill({ json: [...] })).

🤔 What is the difference between route.fulfill, route.continue and route.abort?

fulfill answers the request with your own response, continue sends it to the real server (optionally modified), and abort blocks it.

🤔 How do I modify a real API response in Playwright?

Call const response = await route.fetch(), change the JSON, then route.fulfill({ response, json }).

🤔 How do I block images or ads in Playwright?

Use a route with route.abort(), for example page.route('**/*.{png,jpg}', r => r.abort()).

🤔 Does page.route work for API tests with the request fixture?

No. Routes intercept traffic from the browser page. Requests sent with the request fixture go directly to the server; see API testing with Playwright.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Mobile Device Emulation in Playwright: iPhone, Android and Responsive Testing

Most of your users are on phones, and Playwright can test your site as an iPhone, Android phone or tablet without any real device. In this lesson you will add mobile projects, write mobile-aware tests, check responsive breakpoints and emulate location, language and offline mode.

📖 What You’ll Learn: what device emulation changes, device descriptors and mobile projects, isMobile, test.use for a single file, tap vs click, responsive breakpoint tests, geolocation, locale, time zone, dark mode and offline emulation, and a mobile testing checklist.


📱 What Is Mobile Emulation?

More than half of web traffic comes from phones. Mobile emulation lets Playwright open your website the way a phone does: small screen, touch input, mobile user agent and high pixel density. It runs in the normal desktop browser engines, so it is fast and needs no real device or Android emulator.

Emulation changes:

PropertyExample (iPhone 13)
viewport390 x 664 CSS pixels
deviceScaleFactor3 (retina)
isMobiletrue (mobile meta viewport is respected)
hasTouchtrue (touch events, tap())
userAgentAn iPhone Safari user agent
defaultBrowserTypewebkit

📝 Note: Emulation tests mobile websites, not native apps. For Android and iOS apps from the app stores, use Appium. For final sign-off on real hardware, use a real-device cloud.


🧭 Add Mobile Projects to the Config

Playwright ships ready-made device descriptors for popular phones and tablets. Add them as projects in playwright.config.ts:

import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  use: { baseURL: 'https://www.saucedemo.com' },
  projects: [
    { name: 'Desktop Chrome', use: { ...devices['Desktop Chrome'] } },
    { name: 'Mobile Chrome',  use: { ...devices['Pixel 5'] } },
    { name: 'Mobile Safari',  use: { ...devices['iPhone 13'] } },
    { name: 'iPad',           use: { ...devices['iPad (gen 7)'] } },
    { name: 'iPhone landscape', use: { ...devices['iPhone 13 landscape'] } },
  ],
});
npx playwright test --project="Mobile Safari"

The full list of device names is in Playwright’s source file deviceDescriptorsSource.json; your editor also autocompletes the names inside devices['...'].


✍️ A Mobile Test

The same test code runs on desktop and mobile. Where behaviour differs, check isMobile:

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

test('logged-in user can open the side menu', async ({ page, isMobile }) => {
  await page.goto('/');
  await page.getByPlaceholder('Username').fill('standard_user');
  await page.getByPlaceholder('Password').fill('secret_sauce');
  await page.getByRole('button', { name: 'Login' }).click();

  await page.locator('#react-burger-menu-btn').click();
  await expect(page.locator('#logout_sidebar_link')).toBeVisible();

  if (isMobile) {
    console.log('Viewport on this device:', page.viewportSize());
  }
});

🎯 Emulate a Device in One File: test.use

To make one file always run as a phone, regardless of the project:

import { test, expect, devices } from '@playwright/test';

test.use({ ...devices['Pixel 5'] });   // must be at the top level of the file

test('mobile login page', async ({ page }) => {
  await page.goto('https://www.saucedemo.com/');
  await expect(page.getByPlaceholder('Username')).toBeVisible();
});

⚠️ Common mistake: Device descriptors include defaultBrowserType, which cannot be changed inside a test.describe block. If you see “Cannot use({ defaultBrowserType }) in a describe group”, move test.use to the top of the file or remove defaultBrowserType from the object.


👆 Touch: tap() vs click()

With hasTouch: true, you can send real touch events:

await page.getByRole('button', { name: 'Login' }).tap();

click() also works on mobile emulation; use tap() when the page listens specifically for touch events (swipe menus, mobile-only gestures).


📐 Test Responsive Breakpoints with Viewports

You do not always need a full device. To check how a layout responds at different widths, set the viewport directly and generate tests with a loop (parameterized tests):

const breakpoints = [
  { name: 'mobile',  width: 375,  height: 812 },
  { name: 'tablet',  width: 768,  height: 1024 },
  { name: 'desktop', width: 1440, height: 900 },
];

for (const bp of breakpoints) {
  test('login form is visible on ' + bp.name, async ({ page }) => {
    await page.setViewportSize({ width: bp.width, height: bp.height });
    await page.goto('https://www.saucedemo.com/');
    await expect(page.locator('.login-box')).toBeVisible();
    await expect(page).toHaveScreenshot('login-' + bp.name + '.png');
  });
}

Combine this with visual regression testing to catch broken responsive layouts.


🌍 Emulate Location, Language, Time Zone, Theme and Offline

Mobile scenarios often depend on context, all of which Playwright can emulate:

test.use({
  geolocation: { latitude: 19.0760, longitude: 72.8777 },  // Mumbai
  permissions: ['geolocation'],
  locale: 'hi-IN',
  timezoneId: 'Asia/Kolkata',
  colorScheme: 'dark',
});

test('shows the nearest store', async ({ page, context }) => {
  await page.goto('https://example.com/store-locator');
  // ...

  await context.setOffline(true);    // simulate losing the network
  await page.reload().catch(() => {}); // the reload fails while offline
  await context.setOffline(false);
});
OptionUse case
geolocation + permissionsStore locators, delivery areas, maps
localeTranslated UI, number and date formats
timezoneIdDates and deadlines across time zones
colorSchemeDark mode styles
context.setOffline(true)Offline banners, retry logic, PWAs

✅ Mobile Testing Checklist

  • Key user journeys pass on at least one Android (Pixel) and one iOS (iPhone) descriptor.
  • Navigation works through the mobile menu, not only desktop links.
  • Forms are usable with the on-screen keyboard layout (no hidden buttons).
  • Tap targets are reachable; no horizontal scrolling at 375 px.
  • Visual baselines exist for the main mobile pages.

📝 Assignment

  1. Add Mobile Chrome (Pixel 5) and Mobile Safari (iPhone 13) projects and run your Sauce Demo login tests on them.
  2. Write a test that logs in and opens the side menu, and log isMobile and the viewport size.
  3. Create a file that always runs as iPad (gen 7) using test.use at the top level.
  4. Use tap() instead of click() for the login button on a touch device.
  5. Generate breakpoint tests for 375, 768 and 1440 px widths with a visual snapshot each.
  6. Bonus: emulate Mumbai geolocation, the hi-IN locale and dark mode, then log navigator.language with page.evaluate.

❓ FAQ

🤔 How do I test a mobile website with Playwright?

Add a project using a device descriptor, for example use: { ...devices['iPhone 13'] }, and run your tests with that project. Playwright emulates the screen, touch, user agent and pixel density.

🤔 Can Playwright test native Android or iOS apps?

No. Playwright tests web apps, including mobile websites through emulation. Use Appium for native apps.

🤔 What is the difference between setViewportSize and a device descriptor?

setViewportSize only changes the window size. A device descriptor also sets touch support, mobile mode, user agent and device scale factor, which affects how the site behaves.

🤔 How do I see the list of Playwright devices?

Type devices[' in your editor to get autocomplete, or look at deviceDescriptorsSource.json in the Playwright repository.

🤔 Why does test.use with a device fail inside describe?

Device descriptors contain defaultBrowserType, which can only be set at the top level of a file or in the config, not inside a describe block.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Cross-Browser Testing with Playwright Projects (Chromium, Firefox, WebKit)

One Playwright test suite can run in Chrome, Edge, Firefox and Safari’s engine without changing a single test. In this lesson you will configure browser projects, test branded browsers, handle browser-specific cases and design a cost-effective cross-browser strategy.

📖 What You’ll Learn: supported browser engines, projects and device presets, running one or several browsers, branded Chrome and Edge channels, the browserName fixture, per-browser settings, a practical CI strategy, and common cross-browser differences.


🌐 Why Cross-Browser Testing?

Your users do not all use Chrome. A layout that works in Chromium can break in Safari, a date picker can behave differently in Firefox, and a CSS feature may be missing in an older engine. Cross-browser testing runs the same tests in several browsers to catch those differences before users do.

Playwright makes this unusually easy: one test suite, one API, three browser engines.

EngineCoversNotes
ChromiumGoogle Chrome, Microsoft Edge, Opera, BraveMost used engine worldwide
FirefoxMozilla FirefoxPlaywright ships a patched Firefox build
WebKitApple Safari (macOS and iOS)Runs on Windows, Linux and macOS through Playwright’s WebKit build

🧭 Projects: One Config, Many Browsers

Browsers are configured as projects in playwright.config.ts. Each test runs once per project:

import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  use: { baseURL: 'https://www.saucedemo.com' },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox',  use: { ...devices['Desktop Firefox'] } },
    { name: 'webkit',   use: { ...devices['Desktop Safari'] } },
  ],
});

The devices presets set a realistic viewport, user agent and device scale factor for each browser. Run the suite:

npx playwright test                                    # all three browsers
npx playwright test --project=firefox                  # one browser
npx playwright test --project=chromium --project=webkit

The HTML report groups results by project, so you can see immediately if a test fails in only one browser.


🏷️ Test Branded Browsers: Chrome and Edge

Playwright’s Chromium is open-source Chromium. To test the actual Google Chrome or Microsoft Edge your users install, use a channel:

projects: [
  { name: 'Google Chrome',  use: { ...devices['Desktop Chrome'], channel: 'chrome' } },
  { name: 'Microsoft Edge', use: { ...devices['Desktop Edge'],   channel: 'msedge' } },
],

If they are not installed on the machine:

npx playwright install chrome
npx playwright install msedge

📝 Note: Branded Safari cannot be automated by Playwright. The WebKit project is the closest equivalent and catches the vast majority of Safari rendering and behaviour issues.


🔧 Browser-Specific Code: browserName

Sometimes a feature does not exist in one browser, or a known browser bug needs a workaround. The browserName fixture tells you which browser is running:

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

test('export button works', async ({ page, browserName }) => {
  test.skip(browserName === 'webkit', 'Export is not supported in WebKit yet, see ticket QA-101');
  // ...
});

test('log the current browser', async ({ browserName }) => {
  console.log('Running in ' + browserName); // 'chromium' | 'firefox' | 'webkit'
});

You can also skip or configure a whole file for one browser:

test.skip(({ browserName }) => browserName === 'firefox', 'Feature not supported in Firefox yet');

⚠️ Common mistake: Keep browser-specific branches rare and always give a reason. If many tests need them, the application probably has a real cross-browser bug that should be reported.


⚙️ Different Settings per Browser

Each project can override any use option, and can include or exclude tests:

projects: [
  { name: 'chromium', use: { ...devices['Desktop Chrome'], viewport: { width: 1920, height: 1080 } } },
  { name: 'firefox',  use: { ...devices['Desktop Firefox'] }, testIgnore: /.*visual\.spec\.ts/ },
  { name: 'webkit',   use: { ...devices['Desktop Safari'] }, retries: 2 },
],

Here visual tests are skipped in Firefox (one baseline set is enough, see visual testing), and WebKit gets extra retries while a known issue is investigated.


🚀 A Practical Cross-Browser Strategy

Running every test in every browser on every commit is slow and usually unnecessary. A common, cost-effective approach:

WhenWhat runs
Every pull requestFull suite in Chromium, @smoke tests in Firefox and WebKit
NightlyFull suite in all browsers, including branded Chrome and Edge
Before a releaseFull suite in all browsers plus mobile emulation

Combine projects with tags (tags and grep):

projects: [
  { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
  { name: 'firefox-smoke', grep: /@smoke/, use: { ...devices['Desktop Firefox'] } },
  { name: 'webkit-smoke',  grep: /@smoke/, use: { ...devices['Desktop Safari'] } },
],

In CI, split browsers across parallel jobs or machines to keep the pipeline fast; this is covered in the parallel execution and GitHub Actions lessons in Module 12.


🐞 Typical Cross-Browser Differences to Watch For

  • Fonts and layout: text wraps differently, so elements move. Prefer role and text locators over position-based ones.
  • Date and number inputs: native pickers differ; fill values instead of clicking calendar widgets.
  • Timing: WebKit and Firefox can be slower on some pages; rely on auto-waiting, never fixed sleeps.
  • Permissions and APIs: clipboard, notifications and some media APIs differ between engines.
  • Downloads and new tabs: behave the same in Playwright’s API, but always assert the result, not the browser UI.

📝 Assignment

  1. Make sure your config has Chromium, Firefox and WebKit projects, run your Sauce Demo tests in all three, and compare the timings in the HTML report.
  2. Add a Google Chrome project with channel: 'chrome' and run only that project.
  3. Log browserName in a test, then skip that test in WebKit with a clear reason.
  4. Create firefox-smoke and webkit-smoke projects that only run @smoke tests.
  5. Exclude visual tests from the Firefox project with testIgnore.
  6. Bonus: write a short “cross-browser strategy” for your project: what runs on pull requests, nightly and before releases.

❓ FAQ

🤔 How do I run Playwright tests in multiple browsers?

Define a project per browser in playwright.config.ts (Chromium, Firefox, WebKit). npx playwright test runs every test once per project.

🤔 How do I run Playwright tests in Google Chrome instead of Chromium?

Add a project with channel: 'chrome' and install Chrome with npx playwright install chrome if needed. Use channel: 'msedge' for Microsoft Edge.

🤔 Does Playwright support Safari?

Playwright tests WebKit, the engine behind Safari, on Windows, Linux and macOS. It does not drive the branded Safari application.

🤔 How do I skip a test in one browser?

Use the browserName fixture: test.skip(browserName === 'webkit', 'reason').

🤔 How do I run tests in only one browser?

Pass --project=chromium (or another project name) on the command line.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Data-Driven (Parameterized) Tests in Playwright with TypeScript

Why write the same test five times when you can write it once and feed it five data sets? In this lesson you will build data-driven Playwright tests with simple loops, typed test data, external JSON and CSV files, and project-level parameters.

📖 What You’ll Learn: what data-driven testing is, parameterizing with for…of, unique test titles, typing data with interfaces, describe blocks per data set, loading data from JSON and CSV, parameterizing projects with fixture options, and best practices.


📊 What Is Data-Driven Testing?

Data-driven (parameterized) testing means writing the test logic once and running it with many sets of data. Instead of four nearly identical login tests, you write one test and feed it four users.

Benefits:

  • Less duplicated code, so fixes happen in one place.
  • Adding a scenario means adding one line of data.
  • Each data set still appears as a separate test in the report, so you see exactly which input failed.

Playwright Test has no special “data provider” annotation. You simply generate tests with a normal loop, which makes it flexible and easy to understand.


🔁 Parameterize with a for…of Loop

All error messages below come from the Sauce Demo login page:

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

const invalidLogins = [
  { name: 'locked out user', username: 'locked_out_user', password: 'secret_sauce', error: 'Sorry, this user has been locked out.' },
  { name: 'wrong password',  username: 'standard_user',   password: 'wrong',        error: 'Username and password do not match' },
  { name: 'empty username',  username: '',                password: 'secret_sauce', error: 'Username is required' },
  { name: 'empty password',  username: 'standard_user',   password: '',             error: 'Password is required' },
];

for (const data of invalidLogins) {
  test('login fails: ' + data.name, async ({ page }) => {
    await page.goto('https://www.saucedemo.com/');
    await page.getByPlaceholder('Username').fill(data.username);
    await page.getByPlaceholder('Password').fill(data.password);
    await page.getByRole('button', { name: 'Login' }).click();
    await expect(page.locator('[data-test="error"]')).toContainText(data.error);
  });
}

Running it produces four tests:

✓ login fails: locked out user
✓ login fails: wrong password
✓ login fails: empty username
✓ login fails: empty password

⚠️ Common mistake: Every test needs a unique title. If two generated tests have the same name, Playwright reports a “duplicate test title” error. Always include a value from the data in the title.


🧾 Type Your Test Data

Give the data a type so mistakes are caught in the editor (TypeScript interfaces):

interface LoginCase {
  name: string;
  username: string;
  password: string;
  error: string;
}

const invalidLogins: LoginCase[] = [
  { name: 'locked out user', username: 'locked_out_user', password: 'secret_sauce', error: 'Sorry, this user has been locked out.' },
  // a typo such as "pasword" now shows a red underline
];

🔀 Another Example: Sorting Options

const sortCases = [
  { option: 'az',   label: 'Name (A to Z)',       firstName: 'Sauce Labs Backpack' },
  { option: 'za',   label: 'Name (Z to A)',       firstName: 'Test.allTheThings() T-Shirt (Red)' },
  { option: 'lohi', label: 'Price (low to high)', firstPrice: '$7.99' },
  { option: 'hilo', label: 'Price (high to low)', firstPrice: '$49.99' },
];

test.describe('product sorting', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('https://www.saucedemo.com/');
    await page.getByPlaceholder('Username').fill('standard_user');
    await page.getByPlaceholder('Password').fill('secret_sauce');
    await page.getByRole('button', { name: 'Login' }).click();
  });

  for (const c of sortCases) {
    test('sort by ' + c.label, async ({ page }) => {
      await page.locator('[data-test="product-sort-container"]').selectOption(c.option);
      if (c.firstName) {
        await expect(page.locator('.inventory_item_name').first()).toHaveText(c.firstName);
      }
      if (c.firstPrice) {
        await expect(page.locator('.inventory_item_price').first()).toHaveText(c.firstPrice);
      }
    });
  }
});

📦 One describe Block per Data Set

When each data set needs several tests, generate a describe block per item:

const users = ['standard_user', 'problem_user', 'performance_glitch_user'];

for (const user of users) {
  test.describe('as ' + user, () => {
    test.beforeEach(async ({ page }) => {
      await page.goto('https://www.saucedemo.com/');
      await page.getByPlaceholder('Username').fill(user);
      await page.getByPlaceholder('Password').fill('secret_sauce');
      await page.getByRole('button', { name: 'Login' }).click();
    });

    test('sees the products page', async ({ page }) => {
      await expect(page.locator('.title')).toHaveText('Products');
    });

    test('can open the cart', async ({ page }) => {
      await page.locator('.shopping_cart_link').click();
      await expect(page).toHaveURL(/cart\.html/);
    });
  });
}

📂 Load Data from External Files

Keep large data sets outside the test file, so non-programmers can maintain them.

JSON

// test-data/invalid-logins.json → [{ "name": "...", "username": "...", "password": "...", "error": "..." }]
import invalidLogins from '../test-data/invalid-logins.json';

for (const data of invalidLogins) {
  test('login fails: ' + data.name, async ({ page }) => { /* ... */ });
}

CSV

import fs from 'fs';
import path from 'path';
import { parse } from 'csv-parse/sync';   // npm install -D csv-parse

const records: { name: string; username: string; password: string; error: string }[] =
  parse(fs.readFileSync(path.join(__dirname, '../test-data/logins.csv')), { columns: true, skip_empty_lines: true });

for (const data of records) {
  test('csv login: ' + data.name, async ({ page }) => { /* ... */ });
}

Full walkthroughs: read test data from JSON and read test data from CSV.

📝 Note: Test data used to generate tests must be available when Playwright collects the tests, so read it at the top level of the file (synchronously). Data loaded inside beforeAll is too late to create new tests.


🧩 Parameterize Whole Projects with Options

Sometimes you want to run the entire suite with different values, for example as different user roles or against different environments. Define a fixture option and set it per project:

// fixtures.ts
import { test as base } from '@playwright/test';

export type TestOptions = { role: string };

export const test = base.extend<TestOptions>({
  role: ['standard_user', { option: true }],   // default value, can be overridden in the config
});
export { expect } from '@playwright/test';
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
import type { TestOptions } from './fixtures';

export default defineConfig<TestOptions>({
  projects: [
    { name: 'standard', use: { ...devices['Desktop Chrome'], role: 'standard_user' } },
    { name: 'problem',  use: { ...devices['Desktop Chrome'], role: 'problem_user' } },
  ],
});
// tests/roles.spec.ts
import { test, expect } from '../fixtures';

test('products page loads', async ({ page, role }) => {
  await page.goto('https://www.saucedemo.com/');
  await page.getByPlaceholder('Username').fill(role);
  await page.getByPlaceholder('Password').fill('secret_sauce');
  await page.getByRole('button', { name: 'Login' }).click();
  await expect(page.locator('.title')).toHaveText('Products');
});

Each test now runs once per project, with a different role. This builds on custom fixtures.


✅ Best Practices

  • Include the distinguishing value in every generated test title.
  • Keep each data row small and focused on one scenario.
  • Type your data with an interface.
  • Put large or frequently changing data in JSON or CSV files.
  • Do not loop inside one test over many inputs: the first failure stops the remaining checks and the report shows one test instead of many.
// ❌ One test, many inputs: stops at the first failure
test('all invalid logins', async ({ page }) => {
  for (const data of invalidLogins) { /* ... */ }
});

📝 Assignment

  1. Create the four invalid-login cases above and run them; confirm the report shows four separate tests.
  2. Add an interface for the data and introduce a deliberate typo to see the editor error.
  3. Move the data into test-data/invalid-logins.json and import it.
  4. Write a parameterized test for the four sorting options.
  5. Generate a describe block per user (standard_user, problem_user) with two tests each.
  6. Bonus: create a role option with { option: true } and two projects that use different roles.

❓ FAQ

🤔 How do I write data-driven tests in Playwright?

Put your data in an array (or load it from JSON or CSV) and create a test for each item with a for...of loop, using a value from the data in the test title.

🤔 Does Playwright have a data provider like TestNG?

Not as an annotation. A normal loop that calls test() for each data item does the same job, and each item appears as a separate test in the report.

🤔 Why do I get a duplicate test title error?

Two generated tests have the same title. Include a unique value from the data, such as a name or id, in each title.

🤔 Can I read test data in beforeAll for parameterized tests?

Not for generating tests. Tests are created when the file is loaded, so read the data at the top level of the file.

🤔 How do I run the whole suite with different parameters?

Define a fixture option with { option: true } and set different values in several projects in the config.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in