Playwright Retries and Flaky Tests: Detect, Debug and Fix Them

Flaky tests destroy trust in automation. In this lesson you will configure retries the right way, detect unstable tests before they reach CI, debug failures with traces, and fix the root causes that make Playwright tests flaky.

📖 What You’ll Learn: what flaky tests are, configuring retries globally and per group, passed vs flaky vs failed, repeat-each and fail-on-flaky-tests, traces on retry, testInfo.retry, the common causes of flakiness with fixes, managing known flaky tests, and a retry policy checklist.


🎲 What Is a Flaky Test?

A flaky test passes sometimes and fails sometimes without any change to the code. Flaky tests are dangerous: teams stop trusting red builds, start re-running pipelines “until green”, and real bugs slip through.

Playwright gives you tools to detect, diagnose and fix flakiness. Retries are part of that toolkit, but they are a safety net, not a cure.


🔁 Configure Retries

By default Playwright does not retry failed tests. Turn retries on in playwright.config.ts:

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

export default defineConfig({
  retries: process.env.CI ? 2 : 0,   // retry twice in CI, never locally
});

Or from the command line, or for one group of tests:

npx playwright test --retries=2
test.describe('payment gateway (third-party sandbox)', () => {
  test.describe.configure({ retries: 3 });
  test('card payment', async ({ page }) => { /* ... */ });
});

How retries work

When a test fails, Playwright discards the worker process and runs the test again in a fresh one, including its beforeAll hooks. The final result is one of:

StatusMeaning
passedPassed on the first attempt
flakyFailed at least once, then passed on a retry
failedFailed on every attempt

The HTML report has a Flaky filter, and the terminal summary lists flaky tests separately. Treat every flaky test as a bug to fix.


🔍 Detect Flaky Tests Before They Reach CI

Run a test many times in a row to see whether it is stable:

npx playwright test tests/cart.spec.ts --repeat-each=10            # 10 runs per test
npx playwright test tests/cart.spec.ts --repeat-each=10 --workers=4 # also under parallel load
npx playwright test --fail-on-flaky-tests --retries=1              # fail the run if any test is flaky

💡 Tip: Run new or changed tests with --repeat-each=10 before opening a pull request. Ten passes in a row is a good first sign of stability.


🔬 Diagnose the Failure with Traces

Record a trace for the retry so you can see exactly what happened in the failed attempt:

use: {
  trace: 'on-first-retry',          // records a trace when a test is retried
  screenshot: 'only-on-failure',
  video: 'retain-on-failure',
},

Open it from the HTML report or with npx playwright show-trace. The trace shows every action, a DOM snapshot before and after, network calls and console errors, so you can compare a passing and a failing attempt. Screenshots and videos are covered in screenshots and video recording.

Inside a test you can also react to retries:

test('import report', async ({ page }, testInfo) => {
  if (testInfo.retry > 0) {
    console.log('Retry #' + testInfo.retry + ': cleaning up data from the previous attempt');
    // e.g. delete the half-imported report through the API
  }
  // ...
});

🧯 Common Causes of Flaky Tests and How to Fix Them

CauseSymptomFix
Hard waits (waitForTimeout)Passes on fast machines, fails on slow CIWait for a condition: web-first assertions, waitForResponse (waits)
Checking a value onceexpect(await el.textContent()) fails while the page is updatingUse await expect(el).toHaveText(), which retries
Missing awaitRandom failures, actions out of orderAwait every action; enable no-floating-promises (async/await)
Tests depend on each otherPass in order, fail alone or in parallelMake each test create its own data and state
Shared test dataTwo parallel tests edit the same user or recordUnique data per test, e.g. add testInfo.workerIndex or a timestamp
Unstable locatorsElement sometimes not found or wrong element clickedRole and test-id locators, no nth() on changing lists (locators)
Animations and overlays“Element intercepts pointer events”Wait for the overlay to be hidden; never use force: true as a fix
Slow or unreliable third-party servicesTimeouts on payment, maps, analyticsMock those requests with page.route (Network Mocking lesson, Module 8)
Environment differencesFails only in CISame browser versions, viewport, time zone and locale in config; run CI in Docker

Example: from flaky to stable

// ❌ Flaky: fixed sleep and a one-time check
await page.getByRole('button', { name: 'Search' }).click();
await page.waitForTimeout(2000);
expect(await page.locator('.result').count()).toBeGreaterThan(0);

// ✅ Stable: wait for the response, then a retrying assertion
const response = page.waitForResponse(r => r.url().includes('/api/search') && r.ok());
await page.getByRole('button', { name: 'Search' }).click();
await response;
await expect(page.locator('.result').first()).toBeVisible();

Example: unique test data per worker

test('register a new user', async ({ page }, testInfo) => {
  const email = 'user_' + testInfo.workerIndex + '_' + Date.now() + '@test.com';
  await page.goto('/register');
  await page.getByLabel('Email').fill(email);
  // ...
});

🏷️ Managing Known Flaky Tests

While you investigate, keep the main pipeline trustworthy:

  • Mark the test with test.fixme() and a link to the ticket, or tag it @flaky and exclude it with --grep-invert @flaky (tags and grep).
  • Give genuinely slow tests more time with test.slow() instead of raising the global timeout (annotations).
  • Track flaky tests over time; a rising count is an early warning about the app or the environment.
test('export to PDF', { tag: '@flaky' }, async ({ page }) => {
  test.fixme(true, 'Flaky in CI, see JIRA QA-123');
  // ...
});

✅ Retry Policy Checklist

  • retries: 0 locally so you notice flakiness immediately.
  • retries: 1 or 2 in CI as a safety net, with trace: 'on-first-retry'.
  • Review the flaky list in every report and fix the root cause.
  • Consider --fail-on-flaky-tests for release pipelines.
  • Never increase retries to hide a problem.

📝 Assignment

  1. Set retries: process.env.CI ? 2 : 0 and trace: 'on-first-retry' in your config.
  2. Write a test that fails randomly (for example expect(Math.random()).toBeGreaterThan(0.5)), run it with --retries=3 and find it under Flaky in the HTML report.
  3. Run one of your real Sauce Demo tests with --repeat-each=10 --workers=4 and confirm it is stable.
  4. Take this flaky snippet and rewrite it to be stable: await page.click('#load'); await page.waitForTimeout(3000); expect(await page.locator('#status').innerText()).toBe('Done');
  5. Log testInfo.retry in a test and observe its value on each attempt.
  6. Bonus: tag one test @flaky, exclude it with grepInvert in the config, and confirm it no longer runs.

❓ FAQ

🤔 How do I retry failed tests in Playwright?

Set retries in playwright.config.ts (for example retries: 2), pass --retries=2 on the command line, or use test.describe.configure({ retries: 2 }) for a group.

🤔 What does “flaky” mean in the Playwright report?

The test failed at least once and then passed on a retry. Playwright reports it separately so you can find and fix unstable tests.

🤔 How do I find flaky tests in Playwright?

Run them repeatedly with --repeat-each=10 (ideally with several workers), and check the Flaky filter in the HTML report from CI runs with retries enabled.

🤔 Should I use retries in Playwright?

Use a small number in CI as a safety net, combined with traces on retry. Keep retries at zero locally, and always fix the root cause of flaky tests.

🤔 What is the most common cause of flaky Playwright tests?

Timing: fixed sleeps, one-time checks instead of web-first assertions, and missing await. Replacing them with auto-waiting actions and retrying assertions fixes most flakiness.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Group, Tag and Filter Playwright Tests (describe, Tags and grep)

As a test suite grows, you need to run the right tests at the right time. In this lesson you will group tests with describe blocks, label them with tags, filter runs with grep, and make those filters permanent in the config and npm scripts.

📖 What You’ll Learn: test.describe and nested groups, the tag option and title tags, a practical tagging strategy, –grep and –grep-invert including AND and OR patterns, grep in config projects, npm scripts, describe.configure and serial mode, focus and skip, and reading tags at runtime.


🗂️ Why Organize Tests?

With ten tests, organization does not matter. With five hundred, it decides whether your team can answer questions like:

  • “Run only the smoke tests before every deployment.”
  • “Run the checkout tests after the payments team changed something.”
  • “Skip the slow tests on pull requests, run them nightly.”

Playwright gives you three tools for this: describe blocks to group tests, tags to label them, and grep to filter what runs.


📦 Group Tests with test.describe

test.describe groups related tests under a title. Groups can be nested, and the titles are combined in reports, for example Cart › Add items › add one product.

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

test.describe('Cart', () => {
  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();
  });

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

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

  test.describe('Remove items', () => {
    test('remove a product', async ({ page }) => {
      await page.locator('[data-test="add-to-cart-sauce-labs-backpack"]').click();
      await page.locator('[data-test="remove-sauce-labs-backpack"]').click();
      await expect(page.locator('.shopping_cart_badge')).toHaveCount(0);
    });
  });
});

Describe blocks also scope hooks, so each group can have its own setup.


🏷️ Tag Tests

A tag is a label that starts with @. Add tags with the tag option (recommended) or directly in the title:

// Option 1: tag details (shown as tags in the HTML report)
test('user can log in', { tag: '@smoke' }, async ({ page }) => {
  // ...
});

test('full checkout flow', { tag: ['@regression', '@checkout'] }, async ({ page }) => {
  // ...
});

// Option 2: tag in the title
test('user can log out @smoke', async ({ page }) => {
  // ...
});

// Tag a whole group
test.describe('Payments', { tag: '@payments' }, () => {
  test('pay by card', async ({ page }) => { /* ... */ });
  test('pay by UPI', async ({ page }) => { /* ... */ });
});

A practical tagging strategy

TagMeaningWhen it runs
@smokeCritical paths, fastEvery commit and deployment
@regressionFull functional coverageNightly or before release
@slowLong testsNightly only
@api / @uiTest typeSeparate CI jobs
@checkout, @searchFeature areaWhen that feature changes
@flakyKnown unstable test under investigationExcluded from blocking runs

💡 Tip: Agree on a short, fixed list of tags with your team and document it. Fifty random tags are as confusing as none.


🔍 Filter Tests with –grep

--grep (short: -g) runs only tests whose full title, including describe titles and tags, matches a regular expression:

npx playwright test --grep @smoke                 # tagged @smoke
npx playwright test -g "add two products"         # by title text
npx playwright test --grep "Cart"                 # every test inside the Cart describe
npx playwright test --grep-invert @slow           # everything except @slow
npx playwright test --grep "@smoke|@api"          # @smoke OR @api
npx playwright test --grep "(?=.*@smoke)(?=.*@checkout)"   # @smoke AND @checkout
npx playwright test --grep @regression --grep-invert @flaky

📝 Note: On Windows PowerShell, keep the quotes around patterns that contain |, otherwise the shell treats it as a pipe.

Check what would run without running it:

npx playwright test --grep @smoke --list

⚙️ Filters in the Config and npm Scripts

Make common filters permanent:

// playwright.config.ts
export default defineConfig({
  grepInvert: /@flaky/,      // never run @flaky tests by default
  projects: [
    { name: 'smoke',      grep: /@smoke/,  use: { ...devices['Desktop Chrome'] } },
    { name: 'regression', grep: /@regression/, use: { ...devices['Desktop Chrome'] } },
  ],
});
{
  "scripts": {
    "test:smoke": "playwright test --grep @smoke",
    "test:regression": "playwright test --grep @regression --grep-invert @flaky",
    "test:api": "playwright test --grep @api"
  }
}

Then npm run test:smoke or npx playwright test --project=smoke. More command options are in Playwright CLI commands.


🧵 Control How a Group Runs: describe.configure

// Run tests in this file in parallel, even if fullyParallel is false
test.describe.configure({ mode: 'parallel' });

// Run tests in order; if one fails, the rest are skipped
test.describe.serial('Checkout wizard', () => {
  test('step 1: shipping', async ({ page }) => { /* ... */ });
  test('step 2: payment', async ({ page }) => { /* ... */ });
});

// Retries and timeout for one group
test.describe('Reports', () => {
  test.describe.configure({ retries: 2, timeout: 60_000 });
  test('export PDF', async ({ page }) => { /* ... */ });
});

⚠️ Common mistake: Serial mode makes tests depend on each other, which slows the suite and spreads one failure to many tests. Prefer independent tests; use serial only for genuinely step-by-step flows.


🎯 Focus and Skip Groups While Developing

test.describe.only('Cart', () => { /* only this group runs */ });
test.describe.skip('Wishlist', () => { /* this group is skipped */ });
test.only('debug this one test', async ({ page }) => { /* ... */ });

Never commit .only: set forbidOnly: !!process.env.CI in the config so CI fails if one slips through. Skipping with conditions, fixme and slow are covered in annotations.


🔎 Read Tags at Runtime

test('tagged test', { tag: '@smoke' }, async ({ page }, testInfo) => {
  console.log(testInfo.tags); // ['@smoke']
});

This is useful in reporters, hooks and integrations with test management tools.


📝 Assignment

  1. Organize your Sauce Demo tests into describe blocks: Login, Cart (with nested Add items and Remove items) and Sorting.
  2. Tag two critical tests @smoke, all tests @regression, and one test @slow.
  3. Run only @smoke tests, then everything except @slow, and use --list to confirm each selection first.
  4. Run tests that are both @regression and @smoke using a lookahead pattern.
  5. Add test:smoke and test:regression scripts to package.json.
  6. Create a smoke project in the config with grep: /@smoke/ and run it with --project=smoke.
  7. Bonus: print testInfo.tags in an afterEach hook for every test.

❓ FAQ

🤔 How do I tag tests in Playwright?

Pass a tag option: test('title', { tag: '@smoke' }, async ({ page }) => {}), or add @smoke to the test title. Tags can also be applied to a whole test.describe block.

🤔 How do I run only smoke tests in Playwright?

Run npx playwright test --grep @smoke, or create a project with grep: /@smoke/ and run it with --project.

🤔 How do I exclude tests in Playwright?

Use --grep-invert @tag on the command line, or grepInvert in the config.

🤔 What does test.describe do in Playwright?

It groups tests under a shared title, scopes hooks and configuration to that group, and makes reports easier to read.

🤔 How do I run Playwright tests in a specific order?

Use test.describe.serial or test.describe.configure({ mode: 'serial' }). Tests then run one after another in declaration order, and the rest are skipped if one fails.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright Hooks: beforeEach, afterEach, beforeAll and afterAll Explained

Hooks let you run setup and cleanup code automatically around your tests, so every test starts from a known state without repeating code. This lesson explains all four Playwright hooks, their scope and order, common pitfalls, and when fixtures are the better choice.

📖 What You’ll Learn: beforeEach and afterEach, acting on failures with testInfo, beforeAll and afterAll with worker fixtures, hook scope inside describe blocks, execution order, titled hooks, hooks vs fixtures, and best practices.


🪝 What Are Hooks?

Hooks are functions that run automatically before or after your tests. They remove repetition: instead of writing the same login steps at the start of ten tests, you write them once in a hook.

Playwright Test has four hooks:

HookRunsTypical use
test.beforeEachBefore every test in its scopeOpen the page, log in
test.afterEachAfter every test in its scopeLog results, clean up data, extra screenshots
test.beforeAllOnce, before all tests in its scope (per worker)Create test data via API, start a service
test.afterAllOnce, after all tests in its scope (per worker)Delete test data, close connections

🔁 beforeEach and afterEach

The most common hook. Here every test starts on the logged-in products page:

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

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();
  await expect(page.locator('.title')).toHaveText('Products');
});

test.afterEach(async ({ page }, testInfo) => {
  console.log(testInfo.title + ' finished with status: ' + testInfo.status);
});

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

test('sort products by price', async ({ page }) => {
  await page.locator('[data-test="product-sort-container"]').selectOption('lohi');
  await expect(page.locator('.inventory_item_price').first()).toHaveText('$7.99');
});

Hooks receive the same fixtures as tests (page, context, request…). The second argument, testInfo, describes the current test: its title, status, retry number and more.

Do something only when a test fails

test.afterEach(async ({ page }, testInfo) => {
  if (testInfo.status !== testInfo.expectedStatus) {
    const image = await page.screenshot({ fullPage: true });
    await testInfo.attach('failure-full-page', { body: image, contentType: 'image/png' });
    console.log('Failed on URL: ' + page.url());
  }
});

🧱 beforeAll and afterAll

beforeAll runs once before the tests in its scope. It is ideal for expensive setup that tests can share, such as creating data through an API:

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

let postId: number;

test.beforeAll(async ({ request }) => {
  const response = await request.post('https://jsonplaceholder.typicode.com/posts', {
    data: { title: 'Playwright hooks', body: 'demo', userId: 1 },
  });
  expect(response.ok()).toBeTruthy();
  postId = (await response.json()).id;
  console.log('Created post ' + postId);
});

test.afterAll(async ({ request }) => {
  await request.delete('https://jsonplaceholder.typicode.com/posts/' + postId);
  console.log('Deleted post ' + postId);
});

test('post id was created', async () => {
  expect(postId).toBeGreaterThan(0);
});

⚠️ Common mistake: beforeAll and afterAll can only use worker-scoped fixtures such as browser and request. The page fixture belongs to a single test and is not available in beforeAll. If you need a page there, create one: const page = await browser.newPage(), and close it in afterAll.

📝 Note: “Once” means once per worker process. With four parallel workers, a top-level beforeAll in a file can run up to four times, and it runs again after a failed test, because Playwright restarts the worker. For setup that must run exactly once for the whole run, use a setup project or globalSetup (config file).


📦 Hook Scope with test.describe

Hooks declared at the top of a file apply to every test in the file. Hooks inside a test.describe block apply only to the tests in that block:

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

test.beforeEach(async ({ page }) => {
  await page.goto('https://www.saucedemo.com/');            // runs for ALL tests in the file
});

test.describe('valid login', () => {
  test.beforeEach(async ({ page }) => {                      // runs only in this block
    await page.getByPlaceholder('Username').fill('standard_user');
    await page.getByPlaceholder('Password').fill('secret_sauce');
    await page.getByRole('button', { name: 'Login' }).click();
  });

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

test.describe('invalid login', () => {
  test('locked out user sees an error', async ({ page }) => {
    await page.getByPlaceholder('Username').fill('locked_out_user');
    await page.getByPlaceholder('Password').fill('secret_sauce');
    await page.getByRole('button', { name: 'Login' }).click();
    await expect(page.locator('[data-test="error"]')).toContainText('locked out');
  });
});

🔢 Execution Order

For a test inside a describe block, Playwright runs:

  1. File-level beforeAll (once per worker)
  2. Describe-level beforeAll (once per worker)
  3. File-level beforeEach
  4. Describe-level beforeEach
  5. The test
  6. Describe-level afterEach
  7. File-level afterEach
  8. Describe-level afterAll (after the last test in the block)
  9. File-level afterAll (after the last test in the file)

Before hooks run from the outside in; after hooks run from the inside out.

// Hooks can have titles, which appear in the report and traces
test.beforeEach('open the login page', async ({ page }) => {
  await page.goto('https://www.saucedemo.com/');
});

⚖️ Hooks vs Fixtures

Both remove repetition, but they work differently:

HooksFixtures
Reuse across filesCopy or import per fileDefined once, used anywhere
Setup and teardown togetherSplit into before and afterIn one function around use()
RunsFor every test in scopeOnly for tests that request it
Passes data to testsThrough shared variablesDirectly as a parameter
Best forSimple, file-specific setupReusable setup: logged-in pages, page objects, test data

Start with hooks while learning. As your suite grows, move shared setup into custom fixtures.


✅ Best Practices

  • Keep hooks short; tests should still be readable without scrolling up.
  • Do not share mutable state between tests through beforeAll variables unless tests run in serial mode; each test should work alone.
  • Put assertions in hooks only to confirm setup succeeded (for example, login reached the products page).
  • Use afterEach cleanup for data your test creates, so reruns start fresh.
  • Prefer a setup project with storageState over logging in through the UI in every beforeEach for large suites (save login session).

📝 Assignment

  1. Create tests/hooks.spec.ts with a beforeEach that logs in to Sauce Demo, and three tests: add to cart, sort by price, open the cart.
  2. Add an afterEach that prints the test title and status, and attaches a full-page screenshot only when a test fails.
  3. Add beforeAll and afterAll hooks that print a message; run with --workers=1 and then --workers=3 and explain the difference in output.
  4. Wrap two tests in a test.describe with their own beforeEach, and write down the execution order you observe.
  5. Use beforeAll with the request fixture to create a post on jsonplaceholder.typicode.com and assert its id in a test.
  6. Bonus: try to use page inside beforeAll, read the error, then fix it with browser.newPage().

❓ FAQ

🤔 What is the difference between beforeEach and beforeAll in Playwright?

beforeEach runs before every test and can use the page fixture. beforeAll runs once per worker before all tests in its scope and can only use worker-scoped fixtures such as browser and request.

🤔 Why can’t I use page in beforeAll?

The page fixture is created fresh for each test, so it does not exist yet in beforeAll. Create a page manually with browser.newPage() if you need one.

🤔 Why does my beforeAll run more than once?

beforeAll runs once per worker. With several workers, or after a test failure that restarts the worker, it runs again. Use globalSetup or a setup project for one-time setup.

🤔 Should I use hooks or fixtures in Playwright?

Hooks are fine for simple setup within a file. Fixtures are better for reusable setup across files, because they combine setup and teardown and only run for tests that use them.

🤔 How do I know if a test failed inside afterEach?

Compare testInfo.status with testInfo.expectedStatus; if they differ, the test failed unexpectedly.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Visual Regression Testing in Playwright with toHaveScreenshot

Functional tests miss broken layouts, missing icons and CSS mistakes. Playwright catches them with built-in visual comparisons. In this lesson you will create baselines, compare pages and components, tune tolerances, mask dynamic content and keep results consistent in CI.

📖 What You’ll Learn: what visual regression testing is, toHaveScreenshot for pages and elements, how baselines are stored and updated, maxDiffPixels and threshold, masking and animations, stylePath, cross-platform consistency, and text and ARIA snapshots.


👀 What Is Visual Regression Testing?

Functional tests check that things work: the button submits, the total is correct. They do not notice that the button is now white on white, the logo moved, or a CSS change broke the layout. Visual regression testing catches those problems by comparing screenshots of your application with approved baseline images, pixel by pixel.

Playwright has visual testing built in with toHaveScreenshot(). No extra library or paid service is needed.


🖼️ Your First Visual Test

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

test('login page looks correct', async ({ page }) => {
  await page.goto('https://www.saucedemo.com/');
  await expect(page).toHaveScreenshot('login-page.png');
});

What happens on each run

  1. First run: there is no baseline yet, so the test fails with a message that the snapshot does not exist, and Playwright writes the screenshot as the new baseline.
  2. Second run: Playwright takes a new screenshot and compares it with the baseline. If they match, the test passes.
  3. When the UI changes: the test fails and the HTML report shows Expected, Actual and Diff images, with a slider to compare them.

Baselines are saved next to the test file:

tests/
├── visual.spec.ts
└── visual.spec.ts-snapshots/
    ├── login-page-chromium-win32.png
    ├── login-page-firefox-win32.png
    └── login-page-webkit-win32.png

The file name includes the project (browser) and the platform, because fonts and rendering differ between browsers and operating systems.

💡 Tip: Commit the -snapshots folders to Git. Baselines are part of your test suite, and reviewers can see image changes in pull requests.


🔄 Updating Baselines After an Intended Change

When the design changes on purpose, regenerate the baselines:

npx playwright test --update-snapshots
npx playwright test visual.spec.ts --update-snapshots   # only one file

Review the new images before committing them: an update accepts whatever the page looks like now, including bugs.


🧩 Screenshot a Single Component

Comparing the whole page makes tests sensitive to any change anywhere. Comparing one element keeps visual tests focused:

test('login form component', async ({ page }) => {
  await page.goto('https://www.saucedemo.com/');
  await expect(page.locator('.login-box')).toHaveScreenshot('login-form.png');
});

test('full page including content below the fold', async ({ page }) => {
  await page.goto('https://www.saucedemo.com/');
  await expect(page).toHaveScreenshot('login-full.png', { fullPage: true });
});

🎚️ Tolerances: Avoid False Failures

Tiny rendering differences (anti-aliasing, font smoothing) can produce a few different pixels. Control how strict the comparison is:

OptionMeaningExample
maxDiffPixelsAllowed number of different pixels100
maxDiffPixelRatioAllowed share of different pixels (0 to 1)0.01 (1 percent)
thresholdHow different a pixel’s colour must be to count (0 to 1, default 0.2)0.3
await expect(page).toHaveScreenshot('dashboard.png', { maxDiffPixelRatio: 0.01 });

Set defaults for every visual assertion in playwright.config.ts:

export default defineConfig({
  expect: {
    toHaveScreenshot: { maxDiffPixels: 50 },
  },
});

🎭 Handle Dynamic Content: Mask, Animations and Styles

Dates, ads, avatars, carousels and blinking cursors change on every run. Hide them so they do not cause failures:

await expect(page).toHaveScreenshot('home.png', {
  mask: [page.locator('.current-date'), page.locator('.ad-banner')], // covered with a solid box
  animations: 'disabled',  // finishes or stops CSS animations (default for toHaveScreenshot)
  caret: 'hide',           // hides the text cursor (default)
});

You can also inject CSS only for screenshots, for example to hide a chat widget:

await expect(page).toHaveScreenshot('home.png', {
  stylePath: 'tests/screenshot.css', // e.g. .chat-widget { visibility: hidden; }
});

📝 Note: toHaveScreenshot waits until two consecutive screenshots are identical before comparing, so pages that are still loading are handled automatically. Very dynamic pages still need masking.


🖥️ Consistent Results Locally and in CI

The most common visual testing problem: baselines created on Windows fail on a Linux CI machine because fonts render differently. Solutions:

  • Create baselines in the same environment as CI, for example in the official Playwright Docker image (mcr.microsoft.com/playwright). See Playwright with Docker.
  • Keep platform-specific baselines (the default naming already separates them by OS).
  • Run visual tests in one browser project (usually Chromium) to reduce the number of baselines.
  • Fix the viewport size in the config so layouts are identical.
// Run visual tests only in Chromium with a fixed viewport
projects: [
  { name: 'visual', testMatch: /.*visual\.spec\.ts/, use: { ...devices['Desktop Chrome'], viewport: { width: 1280, height: 720 } } },
  { name: 'chromium', testIgnore: /.*visual\.spec\.ts/, use: { ...devices['Desktop Chrome'] } },
],

📄 Beyond Images: Text and ARIA Snapshots

  • expect(value).toMatchSnapshot('name.txt') compares text or binary data with a stored snapshot.
  • expect(locator).toMatchAriaSnapshot(...) compares the accessibility tree (roles and names) instead of pixels. It is less fragile than images for checking page structure.

✅ Visual Testing Best Practices

  • Start small: key pages and shared components (header, login form, checkout summary).
  • Prefer element screenshots over full pages.
  • Mask anything dynamic; never accept flaky baselines.
  • Review every --update-snapshots change like code.
  • Keep visual tests in a separate file or project so they can run on their own.

📝 Assignment

  1. Write a visual test for the Sauce Demo login page, run it twice, and find the baseline image in the -snapshots folder.
  2. Add an element visual test for .login-box.
  3. Break the baseline on purpose: run once with await page.setViewportSize({ width: 800, height: 600 }) before the screenshot, then open the HTML report and study the Expected, Actual and Diff views.
  4. Add maxDiffPixels: 50 as a default in the config.
  5. Mask the .login_credentials_wrap section and regenerate the baseline with --update-snapshots.
  6. Bonus: create a visual project that runs only *visual.spec.ts files in Chromium with a fixed viewport.

❓ FAQ

🤔 How do I do visual testing in Playwright?

Use await expect(page).toHaveScreenshot('name.png') or await expect(locator).toHaveScreenshot(). The first run creates the baseline; later runs compare against it.

🤔 Why does my visual test fail on the first run?

There is no baseline yet. Playwright writes the current screenshot as the baseline and reports the missing snapshot. Run the test again and it will compare against the new baseline.

🤔 How do I update Playwright screenshots?

Run npx playwright test --update-snapshots (or -u), review the new images, and commit them.

🤔 What is the difference between page.screenshot and toHaveScreenshot?

page.screenshot() just saves an image. toHaveScreenshot() is an assertion that compares the page with a stored baseline and fails if they differ. See screenshots and videos.

🤔 Why do visual tests pass locally but fail in CI?

Different operating systems and fonts render pixels differently. Generate baselines in the same environment as CI (for example the Playwright Docker image) and use small tolerances.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright Screenshots and Video Recording: Complete Guide

Screenshots and videos turn a confusing test failure into an obvious one. In this lesson you will capture full-page and element screenshots, mask sensitive data, attach images to the HTML report, and configure automatic screenshots and videos for failed tests.

📖 What You’ll Learn: page and element screenshots, screenshot options (fullPage, clip, mask, animations), attaching images with testInfo.attach, automatic screenshots and videos in the config, video size, recording in plain scripts, and screenshots vs videos vs traces.


📸 Why Screenshots and Videos Matter

When a test fails in CI at 2 a.m., the error message alone rarely tells the whole story. A screenshot shows what the page looked like at the moment of failure, and a video shows every step leading up to it. Playwright can capture both automatically, with one line in the config.


🖼️ Take a Screenshot of the Page

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

test('capture the login page', async ({ page }) => {
  await page.goto('https://www.saucedemo.com/');

  await page.screenshot({ path: 'screenshots/login.png' });                  // visible area
  await page.screenshot({ path: 'screenshots/login-full.png', fullPage: true }); // whole scrollable page
});

The folder is created automatically. Paths are relative to where you run the command (usually the project root).

Useful screenshot options

OptionWhat it does
pathWhere to save the file (.png or .jpeg)
fullPage: trueCapture the entire scrollable page
type: 'jpeg' with quality: 80Smaller files
clip: { x, y, width, height }Capture only an area of the page
mask: [locator]Cover sensitive or changing elements with a box
animations: 'disabled'Stop CSS animations for a stable image
omitBackground: trueTransparent background (PNG only)
await page.screenshot({
  path: 'screenshots/masked.png',
  fullPage: true,
  mask: [page.locator('[data-test="username"]'), page.locator('[data-test="password"]')],
  animations: 'disabled',
});

🎯 Screenshot a Single Element

Call screenshot() on a locator to capture just that element:

test('capture the login form only', async ({ page }) => {
  await page.goto('https://www.saucedemo.com/');
  await page.locator('.login-box').screenshot({ path: 'screenshots/login-form.png' });
});

Element screenshots are ideal for bug reports and for visual regression tests of components.


📎 Attach Screenshots to the HTML Report

Saving files to a folder is fine locally, but in a team you want screenshots inside the report. Use testInfo.attach():

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

test('cart badge after adding a product', async ({ page }, testInfo) => {
  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.locator('[data-test="add-to-cart-sauce-labs-backpack"]').click();

  const image = await page.screenshot();               // returns a Buffer when no path is given
  await testInfo.attach('cart-after-add', { body: image, contentType: 'image/png' });

  await expect(page.locator('.shopping_cart_badge')).toHaveText('1');
});

Open the HTML report (npx playwright show-report) and the image appears under Attachments for that test.


⚙️ Automatic Screenshots on Failure (Config)

You do not need to write screenshot code in every test. Set it once in playwright.config.ts:

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

export default defineConfig({
  use: {
    screenshot: 'only-on-failure', // 'off' | 'on' | 'only-on-failure'
  },
});
ValueBehaviourGood for
'off'No automatic screenshots (default)Fast local runs
'on'Screenshot after every testAudits, demos
'only-on-failure'Screenshot only when a test failsRecommended for most projects

Screenshots are saved in test-results/ and embedded in the HTML report.


🎬 Record Videos of Test Runs

Videos are also configured with one option:

use: {
  video: 'retain-on-failure', // 'off' | 'on' | 'retain-on-failure' | 'on-first-retry'
},
ValueBehaviour
'off'No video (default)
'on'Record every test
'retain-on-failure'Record every test, keep only failures
'on-first-retry'Record only when a failed test is retried

To control the resolution:

use: {
  video: { mode: 'retain-on-failure', size: { width: 1280, height: 720 } },
},

Videos are saved as .webm files in test-results/ and can be played directly in the HTML report.

📝 Note: A video is finished only when the browser context closes, which Playwright does at the end of each test. If you need the file path inside a test, use await page.video()?.path().

Recording video outside the test runner

When you use the Playwright library in a plain script, enable recording on the context:

import { chromium } from 'playwright';

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext({ recordVideo: { dir: 'videos/' } });
  const page = await context.newPage();
  await page.goto('https://www.saucedemo.com/');
  await context.close(); // the video is written now
  await browser.close();
})();

🧭 Screenshots, Videos or Traces?

ArtifactShowsCost
ScreenshotOne moment, usually the failureVery small
VideoEvery step as a recordingLarger files, slight slowdown
TraceEvery action, DOM snapshot, network call and console log, step by stepMedium; the most useful for debugging

A balanced setup for most teams:

use: {
  screenshot: 'only-on-failure',
  video: 'retain-on-failure',
  trace: 'on-first-retry',
},

Traces are the most powerful debugging tool of the three. They get their own lesson, Trace Viewer step by step, in Module 11.


✅ Best Practices

  • Use 'only-on-failure' and 'retain-on-failure' to keep CI artifacts small.
  • Mask passwords, personal data and changing content (dates, ads) in screenshots.
  • Do not commit test-results/ or screenshot folders to Git; the default .gitignore already excludes them.
  • In CI, upload playwright-report/ as an artifact so the team can open screenshots and videos (covered in the GitHub Actions lesson).
  • Attach screenshots with testInfo.attach() when a step is important, so they appear in the report next to the test.

📝 Assignment

  1. Take a full-page screenshot of https://www.saucedemo.com and an element screenshot of the login form.
  2. Take a screenshot with the username and password fields masked, and compare it with an unmasked one.
  3. Log in, add two products, and attach a screenshot of the cart page to the HTML report with testInfo.attach().
  4. Configure screenshot: 'only-on-failure' and video: 'retain-on-failure'. Make one test fail on purpose and find both artifacts in the HTML report.
  5. Set the video size to 1280 x 720 and confirm the new resolution.
  6. Bonus: write a plain Node script (no test runner) that records a video of opening three different pages.

❓ FAQ

🤔 How do I take a screenshot in Playwright?

await page.screenshot({ path: 'file.png' }) for the page, add fullPage: true for the whole page, or call locator.screenshot() for one element.

🤔 How do I take a screenshot only when a test fails?

Set use: { screenshot: 'only-on-failure' } in playwright.config.ts. The screenshot is saved in test-results/ and shown in the HTML report.

🤔 How do I record a video in Playwright?

Set use: { video: 'on' } (or 'retain-on-failure') in the config. In a plain script, create the context with recordVideo: { dir: 'videos/' }.

🤔 Where are Playwright screenshots and videos saved?

Automatic ones go to the test-results/ folder (configurable with outputDir) and are linked in the HTML report. Manual screenshots go to the path you provide.

🤔 How do I hide sensitive data in a screenshot?

Pass locators to the mask option: page.screenshot({ mask: [page.locator('#password')] }).


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright Codegen: Record Tests, Pick Locators and Generate Code

Playwright Codegen records your clicks and typing and turns them into test code. In this lesson you will use it from the terminal and VS Code, add assertions while recording, record logged-in flows, and refactor the generated code into a clean, reliable test.

📖 What You’ll Learn: starting codegen, the Inspector toolbar, assertions while recording, options for devices, browsers and test ids, saving and loading sessions, recording in VS Code, page.pause(), and a refactoring checklist for recorded code.


🎥 What Is Playwright Codegen?

Codegen is Playwright’s built-in test recorder. You use the website normally in a browser window, and Playwright writes the test code for every click, fill and navigation in real time. It also helps you:

  • Find the best locator for any element (“Pick locator”).
  • Add assertions by clicking elements (visible, text, value).
  • Learn the Playwright API quickly by watching what code each action produces.

It is a learning and productivity tool, not a replacement for designing tests. You will record, then refactor the code into clean tests.


▶️ Start Codegen from the Terminal

From your Playwright project folder (see Install Playwright):

npx playwright codegen https://www.saucedemo.com

Two windows open:

  1. A browser window where you interact with the site.
  2. The Playwright Inspector, which shows the generated code and a toolbar.

Now log in with standard_user / secret_sauce and add a product to the cart. The Inspector writes code like this:

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

test('test', async ({ page }) => {
  await page.goto('https://www.saucedemo.com/');
  await page.locator('[data-test="username"]').click();
  await page.locator('[data-test="username"]').fill('standard_user');
  await page.locator('[data-test="password"]').click();
  await page.locator('[data-test="password"]').fill('secret_sauce');
  await page.locator('[data-test="login-button"]').click();
  await page.locator('[data-test="add-to-cart-sauce-labs-backpack"]').click();
});

The exact locators depend on your Playwright version and the page, but Codegen always prefers stable, user-facing locators: roles, labels, placeholders, text and test ids.


🧰 The Inspector Toolbar

ButtonWhat it does
RecordStart or stop recording actions
Pick locatorHover and click any element to get its locator
Assert visibilityClick an element to add toBeVisible()
Assert textClick an element to add toContainText()
Assert valueClick an input to add toHaveValue()
CopyCopy the generated code
ClearStart a fresh recording
Target dropdownChoose the output language (Playwright Test TypeScript, Python, Java, C#…)

💡 Tip: Use Assert text and Assert visibility while recording. A recorded test without assertions only proves that clicks did not crash; it does not prove that the application worked.


⚙️ Useful Codegen Options

# Save the code straight to a file
npx playwright codegen -o tests/recorded.spec.ts https://www.saucedemo.com

# Emulate a mobile device
npx playwright codegen --device="iPhone 13" https://www.saucedemo.com

# Choose the browser: cr (Chromium), ff (Firefox), wk (WebKit)
npx playwright codegen -b wk https://www.saucedemo.com

# Set the window size, color scheme, language or time zone
npx playwright codegen --viewport-size="1280,720" --color-scheme=dark --lang="en-IN" --timezone="Asia/Kolkata" https://example.com

# Use your own test id attribute in generated locators
npx playwright codegen --test-id-attribute=data-test https://www.saucedemo.com

Record once logged in

Save the session after you log in, then start later recordings already authenticated:

# 1. Log in manually, then close the browser: cookies and storage are saved
npx playwright codegen --save-storage=auth.json https://www.saucedemo.com

# 2. Next recordings start logged in
npx playwright codegen --load-storage=auth.json https://www.saucedemo.com/inventory.html

The same storageState idea is used in real test suites: see save and reuse login sessions.

⚠️ Common mistake: Files like auth.json contain real session cookies. Add them to .gitignore and never commit them.


🧑‍💻 Record from VS Code

With the Playwright Test for VSCode extension:

  • Record new: creates a new test file and opens a browser; actions are written directly into the file.
  • Record at cursor: inserts recorded actions where your cursor is in an existing test.
  • Pick locator: click an element in the browser and the locator is copied into the editor’s locator box.

This is often faster than the terminal, because code lands straight in your project.


⏸️ Record in the Middle of a Test with page.pause()

Add await page.pause() to any test and run it headed. The test stops there and opens the Inspector, where you can record new steps from the current state of the page:

test('extend an existing flow', 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(); // Inspector opens here; click Record to capture the next steps
});
npx playwright test tests/extend.spec.ts --headed

Remove page.pause() before committing the test.


🧹 From Recording to a Real Test: Refactor Checklist

Recorded code is a draft. Turn it into a maintainable test:

  1. Give the test a real name instead of 'test'.
  2. Remove redundant steps such as a click() right before a fill() on the same field.
  3. Add assertions for the outcome of each important step.
  4. Use baseURL and page.goto('/') instead of the full URL (config file).
  5. Move test data out of the code (credentials, product names) into variables or files.
  6. Replace fragile locators like nth(3) with role or text locators (locators, CSS and XPath).
  7. Extract repeated flows (login) into helpers or page objects.

The recorded test above, refactored:

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

const user = { username: 'standard_user', password: 'secret_sauce' };

test('standard user can add a backpack to the cart', async ({ page }) => {
  await page.goto('https://www.saucedemo.com/');
  await page.getByPlaceholder('Username').fill(user.username);
  await page.getByPlaceholder('Password').fill(user.password);
  await page.getByRole('button', { name: 'Login' }).click();
  await expect(page.locator('.title')).toHaveText('Products');

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

⚖️ Codegen: Strengths and Limits

Good forNot good for
Learning the API and locatorsDesigning test structure and coverage
Quickly drafting a happy pathData-driven and negative scenarios
Finding locators on complex pagesReusable code (no page objects or fixtures)
Reproducing a bug reportComplex logic, loops and conditions

📝 Assignment

  1. Run npx playwright codegen https://www.saucedemo.com and record: log in, add two products, open the cart. Save the code to tests/recorded-cart.spec.ts with -o.
  2. While recording, add at least two assertions using Assert text and Assert visibility.
  3. Refactor the recording using the seven-step checklist above, and make it pass headless.
  4. Record the same flow with --device="Pixel 5" and compare any differences in the generated code.
  5. Use --save-storage to save a logged-in session, then start a new recording with --load-storage directly on the inventory page.
  6. Bonus: add page.pause() to your test, record one more step from the Inspector, then remove pause().

❓ FAQ

🤔 What is Playwright codegen?

A built-in recorder that generates Playwright test code while you interact with a website. Start it with npx playwright codegen <url>.

🤔 How do I record a test in Playwright?

Run npx playwright codegen https://your-site.com, perform the actions in the browser, and copy the generated code from the Inspector, or use Record new in the VS Code extension.

🤔 Can Playwright codegen generate TypeScript?

Yes. The default target for Playwright Test is TypeScript/JavaScript, and you can switch to Python, Java or C# in the Inspector’s target dropdown.

🤔 Is codegen code good enough for production tests?

Treat it as a first draft. Rename tests, add assertions, remove redundant steps, move test data out and use page objects before adding it to your suite.

🤔 How do I get a locator for one element without recording?

Use Pick locator in the Inspector or the VS Code extension, then hover and click the element.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright Actions: Click, Fill, Type, Check, Press, Hover and More

Locators find elements; actions make things happen. In this lesson you will learn every Playwright action a tester needs, how auto-waiting protects each one, and which method to choose, with runnable examples on free practice pages.

📖 What You’ll Learn: actionability checks, click options, dblclick and right-click, fill vs pressSequentially, clear, press and the keyboard API, check/uncheck/setChecked, hover, focus, drag and drop, scrolling, and reading values from the page.


🤖 How Playwright Actions Work

An action is anything a user does: click, type, tick a checkbox, press a key, hover, drag. In Playwright you call actions on a locator, and Playwright handles the timing for you.

Before each action, Playwright runs actionability checks and waits until they pass (up to the timeout):

Checkclickfillcheckhover
Attached to the DOM✅✅✅✅
Visible✅✅✅✅
Stable (not animating)✅✅✅
Receives events (not covered)✅✅✅
Enabled✅✅✅
Editable✅

This is why you do not need sleeps before clicks. If a check never passes, the error tells you exactly which one failed, for example “element is not visible” or “another element would receive the click”. Learn more in Playwright waits.


🖱️ click() and Its Options

const login = page.getByRole('button', { name: 'Login' });

await login.click();                                  // left click
await login.click({ button: 'right' });              // right click
await login.click({ clickCount: 2 });                 // same as dblclick()
await login.dblclick();                               // double click
await login.click({ modifiers: ['Shift'] });          // Shift + click ('Control', 'Alt', 'Meta')
await login.click({ position: { x: 5, y: 5 } });      // click a specific point
await login.click({ trial: true });                   // run checks only, do not click

Example on a practice page that adds a button every time you click:

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

test('add three elements', async ({ page }) => {
  await page.goto('https://the-internet.herokuapp.com/add_remove_elements/');
  const add = page.getByRole('button', { name: 'Add Element' });

  for (let i = 0; i < 3; i++) {
    await add.click();
  }
  await expect(page.locator('.added-manually')).toHaveCount(3);

  await page.locator('.added-manually').first().click(); // delete one
  await expect(page.locator('.added-manually')).toHaveCount(2);
});

⚠️ Common mistake: Avoid click({ force: true }). It skips the actionability checks and clicks even when the element is hidden or covered, so your test can pass while a real user would be blocked. Fix the cause (wait for the overlay to disappear) instead.


⌨️ Typing Text: fill(), clear() and pressSequentially()

const username = page.getByPlaceholder('Username');

await username.fill('standard_user');     // clears the field, then sets the value in one step
await username.clear();                   // empties the field
await username.pressSequentially('standard_user', { delay: 100 }); // types key by key
MethodUse it when
fill()Almost always: fastest and most reliable for inputs and textareas
pressSequentially()The page reacts to each keystroke (autocomplete, live search, input masks)
clear()You need an empty field

📝 Note: locator.type() is deprecated. Use fill(), or pressSequentially() when you really need individual key events.

Verify what was typed with toHaveValue:

test('number input', async ({ page }) => {
  await page.goto('https://the-internet.herokuapp.com/inputs');
  const number = page.locator('input[type="number"]');

  await number.fill('42');
  await expect(number).toHaveValue('42');

  await number.press('ArrowUp');           // increments the number input
  await expect(number).toHaveValue('43');
});

🔑 Pressing Keys: press() and page.keyboard

await page.getByLabel('Search').press('Enter');
await page.getByLabel('Search').press('Control+A');   // key combination
await page.getByLabel('Search').press('Backspace');

// Page-level keyboard (acts on whatever has focus)
await page.keyboard.press('Tab');
await page.keyboard.type('Hello');
await page.keyboard.down('Shift');
await page.keyboard.press('ArrowLeft');
await page.keyboard.up('Shift');

Common key names: Enter, Tab, Escape, Backspace, Delete, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, Home, End, PageDown, F1 to F12, and modifiers Shift, Control, Alt, Meta. Use ControlOrMeta for shortcuts that are Ctrl on Windows/Linux and Cmd on macOS.

test('key press is detected', async ({ page }) => {
  await page.goto('https://the-internet.herokuapp.com/key_presses');
  await page.locator('#target').press('Escape');
  await expect(page.locator('#result')).toContainText('You entered:');
});

☑️ Checkboxes and Radio Buttons: check(), uncheck(), setChecked()

test('toggle checkboxes', async ({ page }) => {
  await page.goto('https://the-internet.herokuapp.com/checkboxes');
  const boxes = page.locator('#checkboxes input[type="checkbox"]');

  await boxes.nth(0).check();             // ticks it (no-op if already ticked)
  await expect(boxes.nth(0)).toBeChecked();

  await boxes.nth(1).uncheck();
  await expect(boxes.nth(1)).not.toBeChecked();

  await boxes.nth(1).setChecked(true);     // set to a specific state
  await expect(boxes.nth(1)).toBeChecked();
});

Prefer check() over click() for checkboxes: check() is idempotent and verifies the final state, while click() simply toggles. Radio buttons work the same way: page.getByLabel('Express delivery').check().


🔽 Dropdowns, File Uploads and Dialogs

These have their own detailed lesson, Alerts, Popups, Dropdowns, iFrames and Tabs. Quick reference:

await page.locator('#dropdown').selectOption({ label: 'Option 2' });   // native select
await page.locator('#file-upload').setInputFiles('data/sample.txt');    // upload
page.once('dialog', d => d.accept());                                    // JS alert

🖐️ Hover, Focus, Drag and Scroll

test('hover reveals the caption', async ({ page }) => {
  await page.goto('https://the-internet.herokuapp.com/hovers');
  await page.locator('.figure').nth(1).hover();
  await expect(page.getByText('name: user2')).toBeVisible();
});

test('right-click opens a context-menu alert', async ({ page }) => {
  await page.goto('https://the-internet.herokuapp.com/context_menu');
  page.once('dialog', async dialog => {
    expect(dialog.message()).toBe('You selected a context menu');
    await dialog.accept();
  });
  await page.locator('#hot-spot').click({ button: 'right' });
});
await page.getByLabel('Email').focus();                         // focus without clicking
await page.getByLabel('Email').blur();                          // trigger validation on blur
await page.locator('#source').dragTo(page.locator('#target'));  // drag and drop
await page.getByText('Footer links').scrollIntoViewIfNeeded();  // scroll to an element
await page.mouse.wheel(0, 800);                                 // scroll the page down

Playwright scrolls elements into view automatically before acting, so you rarely need to scroll yourself. Explicit scrolling is useful for infinite-scroll pages and lazy-loaded content.


📖 Reading Values from the Page

Actions often go together with reading data:

MethodReturns
textContent()All text, including hidden text (string or null)
innerText()Visible, rendered text
inputValue()Current value of an input, textarea or select
getAttribute('href')An attribute value
allTextContents()Text of every matching element (string array)
count()Number of matching elements
isVisible(), isChecked(), isEnabled()Current state, checked once without waiting

💡 Tip: To verify something, use web-first assertions such as toHaveText, toHaveValue and toBeChecked. They wait and retry. Use the read methods above only when you need the value for later steps.


📝 Assignment

  1. On https://the-internet.herokuapp.com/add_remove_elements/ add five elements, delete two, and assert three remain.
  2. On https://the-internet.herokuapp.com/checkboxes make both boxes checked using check(), then both unchecked using setChecked(false), with assertions after each step.
  3. On https://the-internet.herokuapp.com/inputs type 100, press ArrowDown three times and assert the value is 97.
  4. On https://the-internet.herokuapp.com/hovers hover each of the three figures in a loop and assert the matching caption (name: user1 to name: user3) is visible.
  5. On https://www.saucedemo.com log in using pressSequentially for the username and press('Enter') in the password field instead of clicking the button.
  6. Bonus: read all three hover captions with allTextContents() and assert the array length is 3.

❓ FAQ

🤔 What is the difference between fill and type in Playwright?

fill() sets the whole value at once and is the recommended method. The old type() is deprecated; its replacement pressSequentially() types key by key for pages that react to each keystroke.

🤔 How do I double-click or right-click in Playwright?

Use locator.dblclick() for a double click and locator.click({ button: 'right' }) for a right click.

🤔 How do I press Enter in Playwright?

await locator.press('Enter') on an element, or await page.keyboard.press('Enter') for whatever has focus.

🤔 Why does Playwright say “element is not visible” or “intercepts pointer events”?

The element is hidden or covered by another element, such as a loader or cookie banner. Wait for the overlay to disappear or close it first, instead of using force: true.

🤔 How do I check a checkbox in Playwright?

await page.getByLabel('Remember me').check(), then verify with await expect(...).toBeChecked().


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

CSS and XPath Selectors in Playwright: Complete Guide with Examples

Role-based locators are the first choice in Playwright, but every real project also needs CSS selectors and XPath. This lesson teaches both from scratch with cheat sheets and runnable examples on real practice pages.

📖 What You’ll Learn: how Playwright detects CSS and XPath, CSS selector syntax, XPath functions and axes, reading table cells three ways, chaining and filtering locators, strict mode, testing selectors in DevTools, and CSS vs XPath.


🧭 Where CSS and XPath Fit in Playwright

Playwright recommends user-facing locators first, such as getByRole, getByLabel and getByText, because they match how users see the page and survive UI refactors. You learned them in Playwright Locators.

But real applications are messy: missing labels, duplicate text, generated tables, legacy markup. That is when CSS selectors and XPath become essential. Both work through page.locator() and get all Playwright benefits: auto-waiting, retries and strictness.

Recommended priority:

  1. getByRole (with accessible name)
  2. getByLabel, getByPlaceholder, getByText, getByAltText, getByTitle
  3. getByTestId (data-testid or your configured attribute)
  4. CSS selector (#id, [data-test=...], stable classes)
  5. XPath (complex relationships, text plus structure, legacy pages)

🔤 How Playwright Detects CSS vs XPath

page.locator('#user-name');                 // CSS (default)
page.locator('//input[@id="user-name"]');   // XPath: starts with //
page.locator('..');                         // XPath: parent of the current element

// Explicit prefixes (optional)
page.locator('css=#user-name');
page.locator('xpath=//input[@id="user-name"]');

Any selector starting with // or .. is treated as XPath; everything else is CSS unless you add a prefix.


🎨 CSS Selectors Cheat Sheet

All examples use the real login page of https://www.saucedemo.com, whose inputs look like this:

<input placeholder="Username" data-test="username" id="user-name" name="user-name" type="text" class="input_error form_input">
<input placeholder="Password" data-test="password" id="password" name="password" type="password" class="input_error form_input">
<input data-test="login-button" id="login-button" type="submit" value="Login" class="submit-button btn_action">
SelectorMatchesExample
#idElement with that id#user-name
.classElement with that class.submit-button
tagAll elements of that taginput
tag.classTag with a classinput.form_input
[attr="value"]Exact attribute value[data-test="password"]
[attr^="v"]Attribute starts with[id^="user"]
[attr$="v"]Attribute ends with[id$="button"]
[attr*="v"]Attribute contains[placeholder*="ser"]
A BB anywhere inside Aform input
A > BB as a direct child of Aform > div
A + BB immediately after Alabel + input
:nth-child(n)The nth child of its parenttr:nth-child(2)
A, BEither A or B#user-name, #password
import { test, expect } from '@playwright/test';

test('login with CSS selectors', async ({ page }) => {
  await page.goto('https://www.saucedemo.com/');
  await page.locator('#user-name').fill('standard_user');
  await page.locator('[data-test="password"]').fill('secret_sauce');
  await page.locator('input[type="submit"]').click();
  await expect(page).toHaveURL(/inventory/);
});

💡 Tip: Prefer ids and test attributes (data-test, data-testid) over classes. Classes such as css-1x2y3z generated by CSS-in-JS libraries change on every build.


🧬 XPath Cheat Sheet

XPathMatches
//inputAny input anywhere
//input[@id='user-name']Input with id user-name
//input[@type='submit' and @value='Login']Both conditions
//input[@id='x' or @name='x']Either condition
//div[text()='Swag Labs']Element whose own text is exactly Swag Labs
//h4[contains(text(),'Accepted')]Text contains a substring
//input[starts-with(@id,'user')]Attribute starts with
//td[normalize-space()='Jason']Text with surrounding spaces trimmed
(//tr)[2]The second tr in the whole document
//td[2]Second td within each row

XPath axes: move around the DOM

Axes are XPath’s superpower: they let you find an element relative to another, which CSS cannot do upwards.

AxisMoves to
parent::tag or ..The parent element
ancestor::tagAny ancestor (parent, grandparent…)
following-sibling::tagSiblings after the element
preceding-sibling::tagSiblings before the element
descendant::tagAny element inside

📊 Real Example: Tables with CSS, XPath and Filters

The practice page https://the-internet.herokuapp.com/tables has a table #table1 with the columns Last Name, First Name, Email, Due, Web Site and Action. Let’s read Jason Doe’s amount due ($100.00) three different ways.

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

test.describe('read a table cell', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('https://the-internet.herokuapp.com/tables');
  });

  test('with CSS nth-child', async ({ page }) => {
    // 3rd row, 4th column (Due)
    const due = page.locator('#table1 tbody tr:nth-child(3) td:nth-child(4)');
    await expect(due).toHaveText('$100.00');
  });

  test('with XPath following-sibling', async ({ page }) => {
    // From the "Jason" cell, the 2nd cell after it is "Due"
    const due = page.locator("//table[@id='table1']//td[text()='Jason']/following-sibling::td[2]");
    await expect(due).toHaveText('$100.00');
  });

  test('with Playwright filter (recommended)', async ({ page }) => {
    const row = page.locator('#table1 tbody tr').filter({ hasText: 'Jason' });
    await expect(row.locator('td').nth(3)).toHaveText('$100.00');
    await expect(page.locator('#table1 tbody tr')).toHaveCount(4);
  });

  test('click edit in the row of a user (XPath parent)', async ({ page }) => {
    await page.locator("//table[@id='table1']//td[text()='Doe']/parent::tr//a[text()='edit']").click();
    await expect(page).toHaveURL(/#edit/);
  });
});

The filter version is the easiest to read: it finds the row by meaningful text instead of a hard-coded row number, so it keeps working when rows are re-ordered or new rows are added. For more table techniques see reading data from web tables.


🔗 Combine Selectors with Playwright Locator Methods

You do not have to put everything in one long selector. Chain and filter instead:

// Chain: find inside another locator
const form = page.locator('form');
await form.locator('#user-name').fill('standard_user');

// Filter by text or by a child element
page.locator('#table1 tbody tr').filter({ hasText: 'Conway' });
page.locator('tr').filter({ has: page.locator('a', { hasText: 'delete' }) });

// Pick from several matches
page.locator('#table1 tbody tr').first();
page.locator('#table1 tbody tr').last();
page.locator('#table1 tbody tr').nth(1);   // zero-based

// Mix CSS and role locators
page.locator('#table1').getByRole('link', { name: 'edit' }).first();

⚠️ Common mistake: Playwright locators are strict: an action like click() fails if the selector matches more than one element. Fix it by making the selector more specific or by using filter, first() or nth() deliberately, not by habit.


🧪 Test Your Selectors Before Using Them

  • Browser DevTools console: document.querySelectorAll('#table1 tbody tr') for CSS, $x("//td[text()='Jason']") for XPath (Chrome).
  • DevTools Elements panel: press Ctrl + F and type a CSS selector or XPath to highlight matches.
  • Playwright Inspector / VS Code “Pick locator”: click an element and Playwright suggests the best locator. See Playwright Codegen.
  • UI mode: npx playwright test --ui lets you try locators against a live snapshot.

⚖️ CSS vs XPath: Which Should You Use?

CSSXPath
ReadabilityShort and familiarLonger
Match by textNot in standard CSS (use filter or getByText)Yes, text() and contains()
Move to parent or ancestorNoYes, with axes
Shadow DOMPlaywright CSS pierces open shadow DOMDoes not pierce shadow DOM
Typical useids, attributes, structuretext plus structure, relative navigation

Rule of thumb: use role-based locators first, CSS for ids and test attributes, and XPath only when you need text-based or upward navigation that filters cannot express.


🚫 Selectors to Avoid

  • Absolute XPath such as /html/body/div[2]/div/form/div[1]/input: breaks with any layout change.
  • Long CSS chains such as div > div > div:nth-child(3) > span.
  • Auto-generated ids and classes (#ember123, .css-1kq9xd).
  • Index-only selectors when a stable text or attribute exists.

📝 Assignment

Use https://www.saucedemo.com and https://the-internet.herokuapp.com/tables:

  1. Write three different CSS selectors for the Sauce Demo password field and use one in a test.
  2. Write an XPath that finds the login button using both @type and @value.
  3. On the tables page, assert that the email of Frank Bach is fbach@yahoo.com using XPath with following-sibling.
  4. Do the same with filter({ hasText }) and nth().
  5. Count the rows of #table1 and assert there are 4.
  6. Click the delete link in Tim Conway’s row using an XPath with parent::tr.
  7. Bonus: rewrite every selector from tasks 1 to 6 using role-based locators where possible, and note which ones were not possible.

❓ FAQ

🤔 How do I use XPath in Playwright?

Pass it to page.locator(): page.locator("//input[@id='user-name']"). Selectors starting with // are detected as XPath automatically, or prefix them with xpath=.

🤔 How do I use a CSS selector in Playwright?

page.locator('#user-name') or page.locator('[data-test="password"]'). CSS is the default selector engine for locator().

🤔 Is XPath slower than CSS in Playwright?

The difference is negligible in practice. Choose based on readability and stability; prefer role-based locators and CSS, and use XPath when you need its axes or text matching.

🤔 Why does XPath not find my element inside a web component?

XPath does not pierce shadow DOM. Use a CSS selector or a role/text locator, which Playwright resolves inside open shadow roots.

🤔 How do I select by text with CSS in Playwright?

Standard CSS cannot match text. Use getByText(), or locator('tr').filter({ hasText: 'Jason' }).


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright CLI Commands: Run, Filter, Debug and Report Tests

Knowing the Playwright command line saves you hours. In this lesson you will learn how to run exactly the tests you want, watch and debug them, control parallelism and retries, generate reports, and turn long commands into simple npm scripts.

📖 What You’ll Learn: running files, folders and single lines, filtering with grep and tags, choosing projects, headed mode, UI mode and the debugger, workers, retries and repeat-each, reporters and traces, codegen and install commands, npm scripts and the VS Code extension.


⌨️ The Basic Command

Every test run starts with:

npx playwright test

npx runs the Playwright version installed in your project. By default this runs all tests, in all projects from your config, headless and in parallel. Everything else in this lesson is an option you add to that command.


📂 Run Specific Files, Folders or Lines

npx playwright test tests/login.spec.ts          # one file
npx playwright test login                         # any file whose path contains "login"
npx playwright test tests/checkout/               # a whole folder
npx playwright test login.spec.ts cart.spec.ts    # several files
npx playwright test tests/login.spec.ts:12        # the test that starts on line 12

🔍 Filter Tests by Name or Tag

npx playwright test -g "locked out user"          # title contains this text (--grep)
npx playwright test --grep "@smoke"               # tests tagged @smoke
npx playwright test --grep-invert "@slow"         # everything except @slow
npx playwright test --grep "@smoke|@regression"   # either tag (regex)

Tags are added in the test title or with the tag option:

test('user can log in', { tag: '@smoke' }, async ({ page }) => {
  // ...
});

Tagging is covered in depth in the lesson on grouping and tagging tests.


🌐 Choose Browsers (Projects)

npx playwright test --project=chromium
npx playwright test --project=chromium --project=firefox
npx playwright test --project="Mobile Chrome"

Project names come from the projects array in playwright.config.ts.


👀 See What Is Happening: Headed, UI Mode and Debug

CommandWhat you get
npx playwright test --headedReal browser windows open while tests run
npx playwright test --uiUI mode: pick tests, watch them, time-travel through each step, re-run on save
npx playwright test --debugPlaywright Inspector: step through the test one action at a time
npx playwright test login.spec.ts:12 --debugDebug one specific test

💡 Tip: UI mode (--ui) is the best way to develop tests. It shows a timeline, DOM snapshots, network calls and console logs for every step, and re-runs tests when you save a file.


⚡ Control Speed, Retries and Failures

npx playwright test --workers=1          # run one test at a time (no parallelism)
npx playwright test --workers=4          # four parallel workers
npx playwright test --retries=2          # retry failed tests twice
npx playwright test -x                   # stop after the first failure
npx playwright test --max-failures=5     # stop after five failures
npx playwright test --timeout=60000      # 60 s per test
npx playwright test --repeat-each=5      # run each test 5 times (find flaky tests)
npx playwright test --last-failed        # re-run only the tests that failed last time

📝 Note: --repeat-each combined with --workers=1 is a quick way to check whether a test is flaky before you push it.


📊 Reports, Traces and Listing Tests

npx playwright test --reporter=list          # one line per test in the terminal
npx playwright test --reporter=dot           # compact output for CI
npx playwright test --reporter=html          # HTML report
npx playwright show-report                   # open the last HTML report
npx playwright test --trace on               # record a trace for every test
npx playwright show-trace test-results/<folder>/trace.zip   # open a trace file
npx playwright test --list                   # list tests without running them

🛠️ Other Useful Playwright Commands

CommandPurpose
npx playwright codegen https://www.saucedemo.comRecord actions and generate test code
npx playwright installDownload or update the browsers
npx playwright install --with-deps chromiumInstall Chromium plus Linux system libraries
npx playwright --versionShow the installed Playwright version
npx playwright test --update-snapshotsUpdate screenshot baselines for visual tests
npx playwright test --shard=1/3Run the first third of the suite (split across CI machines)
npx playwright test --config=api.config.tsUse a different config file
npx playwright test --helpList every option

📦 Save Commands as npm Scripts

Typing long commands is error-prone. Add shortcuts to package.json:

{
  "scripts": {
    "test": "playwright test",
    "test:headed": "playwright test --headed --project=chromium",
    "test:ui": "playwright test --ui",
    "test:smoke": "playwright test --grep @smoke",
    "test:debug": "playwright test --debug",
    "report": "playwright show-report"
  }
}

Now run npm test, npm run test:smoke or npm run report. Inside npm scripts you do not need npx.


🧑‍💻 Running Tests from VS Code

The Playwright Test for VSCode extension gives you the same power with clicks:

  • ▶ next to a test or file runs it; right-click for Debug Test.
  • Show browser runs headed; Show trace viewer opens traces automatically.
  • Select which projects (browsers) to run in the Playwright panel of the Testing view.
  • Pick locator and Record new use the Inspector and Codegen.

Installation is covered in Install Playwright and set up VS Code.


📝 Assignment

Use the login tests you wrote in your first Playwright test:

  1. Run only the “locked out user” test using -g.
  2. Run all login tests only in Firefox, headed.
  3. Open UI mode, run the suite, and use the timeline to inspect the step where the login button is clicked.
  4. Add the tag @smoke to two tests and run only those tests.
  5. Run your suite with --repeat-each=3 --workers=1 and confirm every run passes.
  6. Add test:smoke and report scripts to package.json and use them.

❓ FAQ

🤔 How do I run a specific test in Playwright?

Use the file and line: npx playwright test tests/login.spec.ts:12, or filter by title: npx playwright test -g "test title". In VS Code, click ▶ next to the test.

🤔 How do I run Playwright tests in headed mode?

Add --headed: npx playwright test --headed. Set headless: false in the config to make it the default.

🤔 How do I run Playwright tests in one browser only?

Use --project=chromium (or another project name from your config).

🤔 How do I run tests one by one instead of in parallel?

Use --workers=1. Tests then run sequentially in a single worker process.

🤔 How do I see all Playwright CLI options?

Run npx playwright test --help for test options and npx playwright --help for all commands.

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

playwright.config.ts Explained: Every Important Playwright Config Option

Every Playwright project is controlled by one file: playwright.config.ts. In this lesson you will learn what each important option does, how projects work, and how to build a clean, production-ready config step by step.

📖 What You’ll Learn: test runner options (testDir, timeout, workers, retries, reporter), the use block (baseURL, headless, viewport, screenshot, video, trace, timeouts), projects for browsers and devices, setup projects, webServer, test.use overrides and a complete annotated config.


📄 What Is playwright.config.ts?

playwright.config.ts is the control centre of your Playwright project. It sits in the project root and tells Playwright where your tests are, how to run them, which browsers to use, and what to record when something fails. Because it is a TypeScript file wrapped in defineConfig(), your editor autocompletes every option and flags typos.

Here is the config the installer generates (comments shortened):

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',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox',  use: { ...devices['Desktop Firefox'] } },
    { name: 'webkit',   use: { ...devices['Desktop Safari'] } },
  ],
});

The options fall into three groups: test runner options (top level), browser and context options (inside use), and projects (named variations of use). Let’s go through each.


⚙️ Test Runner Options (Top Level)

OptionWhat it doesExample
testDirFolder that contains your tests'./tests'
testMatch / testIgnoreWhich files count as tests (default: *.spec.ts and *.test.ts)'**/*.e2e.ts'
timeoutMax time for one test, default 30 seconds60_000
expect.timeoutMax time for one assertion, default 5 seconds{ timeout: 10_000 }
fullyParallelRun tests inside a file in parallel tootrue
workersNumber of parallel worker processes4 or '50%'
retriesRe-run failed tests this many times2
forbidOnlyFail the run if test.only was left in code (great for CI)!!process.env.CI
maxFailuresStop the run after N failures10
reporterHow results are reported'html', 'list', or an array
outputDirWhere screenshots, videos and traces are saved'test-results'
globalSetup / globalTeardownFiles that run once before / after all tests'./global-setup.ts'

💡 Tip: process.env.CI is set automatically by most CI systems (including GitHub Actions). The default config uses it to apply stricter settings in CI and faster ones locally.


🌐 The use Block: Browser and Context Options

Everything inside use applies to the browser, context and page that each test receives.

OptionWhat it does
baseURLLets you write page.goto('/login') instead of the full URL
headlessfalse shows the browser window (default true)
viewportBrowser window size, e.g. { width: 1280, height: 720 }
screenshot'off', 'on' or 'only-on-failure'
video'off', 'on', 'retain-on-failure' or 'on-first-retry'
trace'off', 'on', 'retain-on-failure' or 'on-first-retry'
actionTimeoutMax time for each click, fill etc. (default: no separate limit)
navigationTimeoutMax time for goto and navigations
ignoreHTTPSErrorsAccept invalid certificates on test environments
locale / timezoneIdTest in another language or time zone, e.g. 'en-IN', 'Asia/Kolkata'
storageStateStart each test already logged in (see save login session)
testIdAttributeCustom attribute for getByTestId, e.g. 'data-test'
launchOptionsLow-level options such as { slowMo: 500 } to slow down actions

A practical use block for most projects:

use: {
  baseURL: process.env.BASE_URL ?? 'https://www.saucedemo.com',
  headless: true,
  viewport: { width: 1366, height: 768 },
  screenshot: 'only-on-failure',
  video: 'retain-on-failure',
  trace: 'on-first-retry',
  actionTimeout: 15_000,
  testIdAttribute: 'data-test',
},

🧭 Projects: Browsers, Devices and Environments

A project is a named group of settings. Every test runs once per project. Projects are how you run cross-browser tests, mobile emulation, or different environments.

projects: [
  { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
  { name: 'firefox',  use: { ...devices['Desktop Firefox'] } },
  { name: 'webkit',   use: { ...devices['Desktop Safari'] } },

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

  // Mobile emulation
  { name: 'Mobile Safari', use: { ...devices['iPhone 13'] } },
  { name: 'Mobile Chrome', use: { ...devices['Pixel 5'] } },
],

Run a single project with npx playwright test --project=chromium.

Setup project: log in once for all tests

Projects can depend on each other. A common pattern is a setup project that logs in and saves the session, which other projects reuse:

projects: [
  { name: 'setup', testMatch: /.*\.setup\.ts/ },
  {
    name: 'chromium',
    use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/user.json' },
    dependencies: ['setup'],
  },
],

🚀 webServer: Start Your App Before Testing

If you test your own application locally, Playwright can start it for you and wait until it is ready:

webServer: {
  command: 'npm run start',
  url: 'http://localhost:3000',
  reuseExistingServer: !process.env.CI,
  timeout: 120_000,
},

📋 A Complete, Annotated Config for This Course

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

export default defineConfig({
  testDir: './tests',
  timeout: 30_000,
  expect: { timeout: 7_000 },
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 2 : undefined,
  reporter: [
    ['list'],                               // readable terminal output
    ['html', { open: 'never' }],            // HTML report in playwright-report/
  ],
  use: {
    baseURL: process.env.BASE_URL ?? 'https://www.saucedemo.com',
    testIdAttribute: 'data-test',
    screenshot: 'only-on-failure',
    video: 'retain-on-failure',
    trace: 'on-first-retry',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox',  use: { ...devices['Desktop Firefox'] } },
  ],
});

📝 Note: You can keep several config files (for example one for API tests and one for UI tests) and choose one with --config. See multiple config files, and load secrets from a .env file as shown in environment variables with .env.


🎯 Override Config for One File or Test

Settings in the config are defaults. You can override use options for a file or a describe block with test.use():

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

test.use({ viewport: { width: 390, height: 844 }, locale: 'hi-IN' });

test('mobile layout in Hindi locale', async ({ page }) => {
  await page.goto('/');
  // ...
});

And change the timeout of a single test with test.setTimeout(60_000) or test.slow().


📝 Assignment

  1. Set baseURL to https://www.saucedemo.com and update your login test to use page.goto('/').
  2. Change the reporter to show list output in the terminal and generate the HTML report.
  3. Enable screenshots and videos only for failed tests. Break a test on purpose and find the screenshot and video in the HTML report.
  4. Add a Mobile Chrome project using devices['Pixel 5'] and run only that project.
  5. Set retries: 1 locally, make a test fail, and observe the retry and the trace in the report.
  6. Bonus: set testIdAttribute: 'data-test' and replace one locator with page.getByTestId('login-button').

❓ FAQ

🤔 Where is the Playwright config file?

In the project root, named playwright.config.ts (or .js). Playwright finds it automatically; use --config path/to/file.ts to choose another.

🤔 How do I increase the timeout in Playwright?

Set timeout for whole tests and expect: { timeout } for assertions in the config, or call test.setTimeout() in a single test. See Playwright waits for all timeouts.

🤔 How do I run Playwright tests in headed mode by default?

Set use: { headless: false } in the config, or pass --headed on the command line.

🤔 What does workers mean in the Playwright config?

Workers are parallel processes that run tests. workers: 4 runs up to four test files at the same time; undefined lets Playwright use about half of your CPU cores.

🤔 What is the difference between use and projects?

use sets default browser and context options for all tests. Each project adds a name and its own use settings on top, and every test runs once per project.

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in