JavaScript Variables Practice Programs with Solutions (32 Programs)

Practise JavaScript variables with 32 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning JavaScript for Playwright.

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with node program.js.

New to this topic? Read the JavaScript Variables lesson first.

JavaScript Beginner Programs

1. Declare and print variablesBeginner

Declare a variable testerName with your name and a variable experienceYears with a number, then print both.

Show solution
let testerName = 'Asha';
let experienceYears = 3;
console.log('Tester:', testerName);
console.log('Experience (years):', experienceYears);

Output

Tester: Asha
Experience (years): 3

Explanation: let declares a variable that holds a value. console.log prints its arguments separated by a space.

2. Reassign a let variableBeginner

Create browser with the value 'chromium', print it, change it to 'firefox' and print it again.

Show solution
let browser = 'chromium';
console.log('Before:', browser);
browser = 'firefox';
console.log('After:', browser);

Output

Before: chromium
After: firefox

Explanation: variables declared with let can be reassigned. The second assignment replaces the old value.

3. Constants cannot be reassignedBeginner

Store a base URL in a const, then try to reassign it inside try/catch and print the error message.

Show solution
const BASE_URL = 'https://qa.example.com';
try {
  BASE_URL = 'https://prod.example.com';
} catch (error) {
  console.log('Error:', error.message);
}
console.log('BASE_URL is still', BASE_URL);

Output

Error: Assignment to constant variable.
BASE_URL is still https://qa.example.com

Explanation: a const binding cannot be reassigned, so the assignment throws a TypeError. The original value stays unchanged.

4. Swap two variables with a temporary variableBeginner

Swap the values of a = 10 and b = 20 using a third variable and print them before and after.

Show solution
let a = 10;
let b = 20;
console.log('Before swap: a =', a, 'b =', b);
let temp = a;
a = b;
b = temp;
console.log('After swap: a =', a, 'b =', b);

Output

Before swap: a = 10 b = 20
After swap: a = 20 b = 10

Explanation: the temporary variable keeps the first value safe while it is overwritten.

5. Swap two variables with destructuringBeginner

Swap first = 'login' and second = 'logout' without a temporary variable.

Show solution
let first = 'login';
let second = 'logout';
[first, second] = [second, first];
console.log(first, second);

Output

logout login

Explanation: array destructuring builds a temporary array [second, first] and unpacks it back into the two variables in one step.

6. Declare several variables in one statementBeginner

Declare passed, failed and skipped test counts in a single let statement and print the total.

Show solution
let passed = 42, failed = 3, skipped = 5;
let total = passed + failed + skipped;
console.log('Total tests:', total);

Output

Total tests: 50

Explanation: one let can declare several comma-separated variables. Readability usually favours one per line in real projects.

7. Uninitialised variableBeginner

Declare result without a value and print it and its type.

Show solution
let result;
console.log(result);
console.log(typeof result);

Output

undefined
undefined

Explanation: a declared but unassigned variable holds undefined, whose type is also 'undefined'.

8. Build a message with a template literalBeginner

Use variables user = 'qa_admin' and role = 'Admin' to print Logged in as qa_admin (Admin).

Show solution
const user = 'qa_admin';
const role = 'Admin';
const message = `Logged in as ${user} (${role})`;
console.log(message);

Output

Logged in as qa_admin (Admin)

Explanation: template literals (backticks) insert variable values with ${...}.

9. Increment a counterBeginner

Start retryCount at 0, increase it three times using different syntax and print it after each step.

Show solution
let retryCount = 0;
retryCount = retryCount + 1;
console.log(retryCount);
retryCount += 1;
console.log(retryCount);
retryCount++;
console.log(retryCount);

Output

1
2
3

Explanation: x = x + 1, x += 1 and x++ all add one to a let variable.

10. Valid variable namesBeginner

Create variables named with camelCase, a leading underscore and a dollar sign, then print them together.

Show solution
const firstName = 'Ravi';
const _internalId = 101;
const $price = 499;
console.log(firstName, _internalId, $price);

Output

Ravi 101 499

Explanation: names may start with a letter, _ or $, and must not start with a digit. camelCase is the usual convention.

JavaScript Intermediate Programs

11. Block scope with letIntermediate

Declare status outside an if block and a different status inside it. Print both to show they are separate.

Show solution
let status = 'outer';
if (true) {
  let status = 'inner';
  console.log('Inside block:', status);
}
console.log('Outside block:', status);

Output

Inside block: inner
Outside block: outer

Explanation: let is block-scoped, so the inner status exists only inside the braces and does not affect the outer one.

12. var ignores block scopeIntermediate

Repeat the previous program using var and observe the difference.

Show solution
var status = 'outer';
if (true) {
  var status = 'inner';
  console.log('Inside block:', status);
}
console.log('Outside block:', status);

Output

Inside block: inner
Outside block: inner

Explanation: var is function-scoped, so both declarations refer to the same variable and the block overwrites it.

13. Hoisting with varIntermediate

Print a var variable before the line that declares it.

Show solution
console.log('Before declaration:', environment);
var environment = 'staging';
console.log('After declaration:', environment);

Output

Before declaration: undefined
After declaration: staging

Explanation: var declarations are hoisted and initialised with undefined, so the first log prints undefined instead of throwing.

14. Temporal dead zone with letIntermediate

Access a let variable before its declaration inside try/catch and print the error name.

Show solution
try {
  console.log(timeout);
  let timeout = 30000;
} catch (error) {
  console.log(error.name + ': ' + error.message);
}

Output

ReferenceError: Cannot access 'timeout' before initialization

Explanation: let and const are hoisted but not initialised. Using them before the declaration throws a ReferenceError (the temporal dead zone).

15. const object can still changeIntermediate

Store test settings in a const object, change one property and print the object.

Show solution
const settings = { headless: true, retries: 0 };
settings.retries = 2;
console.log(settings);

Output

{ headless: true, retries: 2 }

Explanation: const stops reassignment of the variable, not changes to the object it points to.

16. Freeze a configuration objectIntermediate

Freeze a config object, try to change it and print it to show the change was ignored.

Show solution
const config = Object.freeze({ browser: 'chromium', workers: 4 });
config.workers = 8;
console.log(config.workers);
console.log(Object.isFrozen(config));

Output

4
true

Explanation: Object.freeze makes properties read-only. In non-strict code the assignment is silently ignored.

17. Loop variable scope: let vs varIntermediate

Collect functions in a loop using let and using var, then call them to see which values they remember.

Show solution
const withLet = [];
for (let i = 0; i < 3; i++) withLet.push(() => i);
const withVar = [];
for (var j = 0; j < 3; j++) withVar.push(() => j);
console.log('let:', withLet.map(f => f()));
console.log('var:', withVar.map(f => f()));

Output

let: [ 0, 1, 2 ]
var: [ 3, 3, 3 ]

Explanation: let creates a new binding for each loop iteration. var shares one variable, so every function sees its final value 3.

18. Shadowing in nested blocksIntermediate

Use the same name level in three nested scopes and print it from each one.

Show solution
const level = 'file';
{
  const level = 'block';
  {
    const level = 'nested block';
    console.log(level);
  }
  console.log(level);
}
console.log(level);

Output

nested block
block
file

Explanation: an inner declaration shadows outer ones with the same name. Each scope sees its nearest declaration.

19. Variables copy primitives by valueIntermediate

Copy a number into another variable, change the copy and print both.

Show solution
let originalTimeout = 5000;
let copiedTimeout = originalTimeout;
copiedTimeout = 10000;
console.log('original:', originalTimeout);
console.log('copy:', copiedTimeout);

Output

original: 5000
copy: 10000

Explanation: primitives such as numbers are copied by value, so changing the copy does not affect the original.

20. Variables share objects by referenceIntermediate

Assign an object to a second variable, change it through the second variable and print the first.

Show solution
const user = { name: 'Asha', active: true };
const sameUser = user;
sameUser.active = false;
console.log(user.active);
console.log(user === sameUser);

Output

false
true

Explanation: both variables point to the same object, so a change through either one is visible through both.

JavaScript Real-World QA Scenario Programs

21. Store environment URLsReal-world

Store base URLs for qa, staging and prod in constants, pick one with a selectedEnv variable and print the login URL.

Show solution
const QA_URL = 'https://qa.shop.test';
const STAGING_URL = 'https://staging.shop.test';
const PROD_URL = 'https://shop.test';
const selectedEnv = 'staging';
const baseUrl = selectedEnv === 'qa' ? QA_URL : selectedEnv === 'staging' ? STAGING_URL : PROD_URL;
const loginUrl = `${baseUrl}/login`;
console.log(loginUrl);

Output

https://staging.shop.test/login

Explanation: constants keep fixed values in one place, and a single variable decides which environment the test uses.

22. Build unique test dataReal-world

Create a unique email for a sign-up test using a fixed runId variable and a username prefix.

Show solution
const prefix = 'qa.user';
const runId = 1730275200;
const email = `${prefix}+${runId}@example.com`;
console.log(email);

Output

qa.user+1730275200@example.com

Explanation: combining a stable prefix with a run ID gives unique but readable test data. In real tests the ID could come from Date.now().

23. Count test resultsReal-world

Use counter variables to tally the statuses ['passed', 'failed', 'passed', 'skipped', 'passed'].

Show solution
const statuses = ['passed', 'failed', 'passed', 'skipped', 'passed'];
let passed = 0, failed = 0, skipped = 0;
for (const status of statuses) {
  if (status === 'passed') passed++;
  else if (status === 'failed') failed++;
  else skipped++;
}
console.log(`Passed: ${passed}, Failed: ${failed}, Skipped: ${skipped}`);

Output

Passed: 3, Failed: 1, Skipped: 1

Explanation: counters declared with let are updated inside the loop. The loop variable status is a fresh const each time.

24. Calculate a pass percentageReal-world

With total = 80 and failed = 6, calculate and print the pass percentage rounded to one decimal place.

Show solution
const total = 80;
const failed = 6;
const passed = total - failed;
const passRate = (passed / total) * 100;
console.log(`Pass rate: ${passRate.toFixed(1)}%`);

Output

Pass rate: 92.5%

Explanation: intermediate variables like passed make the calculation readable. toFixed(1) formats the result.

25. Default timeout with fallbackReal-world

A variable customTimeout may be undefined. Use ?? to fall back to a default of 30000 ms and print the timeout used in both cases.

Show solution
const DEFAULT_TIMEOUT = 30000;
let customTimeout;
console.log('Timeout used:', customTimeout ?? DEFAULT_TIMEOUT);
customTimeout = 60000;
console.log('Timeout used:', customTimeout ?? DEFAULT_TIMEOUT);

Output

Timeout used: 30000
Timeout used: 60000

Explanation: ?? returns the right side only when the left side is null or undefined, which makes it ideal for optional settings.

26. Track login attemptsReal-world

Simulate three failed login attempts with a let counter and lock the account when it reaches MAX_ATTEMPTS = 3.

Show solution
const MAX_ATTEMPTS = 3;
let attempts = 0;
let locked = false;
for (let i = 1; i <= 3; i++) {
  attempts++;
  console.log(`Attempt ${attempts} failed`);
  if (attempts === MAX_ATTEMPTS) locked = true;
}
console.log('Account locked:', locked);

Output

Attempt 1 failed
Attempt 2 failed
Attempt 3 failed
Account locked: true

Explanation: a constant holds the business rule and let variables track state that changes during the scenario.

27. Build a test report lineReal-world

Store the test name, duration in milliseconds and status in variables, then print one formatted report line with the duration in seconds.

Show solution
const testName = 'Checkout with saved card';
const durationMs = 2345;
const status = 'PASSED';
const durationSec = (durationMs / 1000).toFixed(2);
console.log(`[${status}] ${testName} (${durationSec}s)`);

Output

[PASSED] Checkout with saved card (2.35s)

Explanation: separate variables for each piece of data keep the formatting step simple and easy to change.

28. Running cart totalReal-world

Add item prices 499, 1299 and 250 to a running cartTotal, printing the total after each item.

Show solution
let cartTotal = 0;
cartTotal += 499;
console.log('After item 1:', cartTotal);
cartTotal += 1299;
console.log('After item 2:', cartTotal);
cartTotal += 250;
console.log('After item 3:', cartTotal);

Output

After item 1: 499
After item 2: 1798
After item 3: 2048

Explanation: += updates the running total in place, which mirrors how a test checks a cart after each step.

29. Mask a password before loggingReal-world

Store a password in a variable and log a masked version that shows only the last two characters.

Show solution
const password = 'Secr3t!Pass';
const masked = '*'.repeat(password.length - 2) + password.slice(-2);
console.log('Password used:', masked);

Output

Password used: *********ss

Explanation: never log real secrets. A derived variable holds a safe version for logs and reports.

30. Read settings with fallbacksReal-world

Given envVars = { BASE_URL: 'https://qa.app.test' }, read BASE_URL and WORKERS into variables, defaulting WORKERS to 2.

Show solution
const envVars = { BASE_URL: 'https://qa.app.test' };
const baseUrl = envVars.BASE_URL ?? 'http://localhost:3000';
const workers = Number(envVars.WORKERS ?? 2);
console.log('baseUrl:', baseUrl);
console.log('workers:', workers);

Output

baseUrl: https://qa.app.test
workers: 2

Explanation: tests often read process.env, where values may be missing. Defaults keep the run predictable.

31. Destructure test data into variablesReal-world

Unpack username, password and an optional role (default 'viewer') from a test-data object.

Show solution
const testUser = { username: 'qa_tester', password: 'P@ss123' };
const { username, password, role = 'viewer' } = testUser;
console.log(username, role);
console.log('Password length:', password.length);

Output

qa_tester viewer
Password length: 7

Explanation: object destructuring creates several variables at once and can supply defaults for missing properties.

32. Rename while destructuringReal-world

An API returns { id: 7, full_name: 'Neha Sharma' }. Store the values in camelCase variables userId and fullName.

Show solution
const apiUser = { id: 7, full_name: 'Neha Sharma' };
const { id: userId, full_name: fullName } = apiUser;
console.log(`User #${userId}: ${fullName}`);

Output

User #7: Neha Sharma

Explanation: property: newName in destructuring renames a value, which keeps your code in camelCase even when an API uses snake_case.

Keep Practising

Playwright Cheat Sheet (TypeScript): Commands, Locators, Assertions and Config

Everything you use daily in Playwright with TypeScript, on one page: commands, locators, actions, assertions, waits, config, fixtures, API testing, debugging and CI. Bookmark it and keep it open while you code.

📖 What You’ll Learn: CLI commands, test structure and annotations, locators, actions, assertions, waits, playwright.config.ts essentials, fixtures and page objects, API testing and network mocking, debugging and reports, a minimal CI workflow, AI tools, and the top 10 mistakes to avoid.


📌 How to Use This Cheat Sheet

A one-page reference for Playwright Test with TypeScript. Each section links to the full lesson in the Playwright Tutorial with TypeScript. To keep a copy, use your browser’s Print, Save as PDF.


⚙️ Setup and CLI

npm init playwright@latest                 # new project (choose TypeScript)
npx playwright install --with-deps         # browsers + Linux dependencies
npx playwright test                        # run all tests
npx playwright test login.spec.ts:12       # one test by line
npx playwright test -g "checkout"          # by title
npx playwright test --grep @smoke          # by tag
npx playwright test --project=firefox      # one browser project
npx playwright test --headed               # visible browser
npx playwright test --ui                   # UI mode
npx playwright test --debug                # Inspector
npx playwright test --workers=4 --retries=2
npx playwright test --repeat-each=10       # find flaky tests
npx playwright test --last-failed
npx playwright test --shard=1/3 --reporter=blob
npx playwright merge-reports --reporter html ./all-blob-reports
npx playwright show-report
npx playwright show-trace trace.zip
npx playwright codegen https://example.com
npx playwright test --update-snapshots

Lessons: install, CLI commands, codegen


🧪 Test Structure

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

test.describe('Cart', { tag: '@regression' }, () => {
  test.beforeEach(async ({ page }) => { await page.goto('/'); });

  test('adds an item', { tag: '@smoke' }, async ({ page }, testInfo) => {
    await test.step('add backpack', async () => { /* ... */ });
  });
});

test.only(...);  test.skip(...);  test.fixme(...);  test.slow();
test.describe.configure({ mode: 'parallel' });   // or 'serial'
test.use({ viewport: { width: 390, height: 844 } });

Lessons: first test, hooks, tags, annotations


🎯 Locators

LocatorExample
Rolepage.getByRole('button', { name: 'Login' })
Labelpage.getByLabel('Email')
Placeholderpage.getByPlaceholder('Username')
Textpage.getByText('Products', { exact: true })
Alt text / titlepage.getByAltText('logo'), page.getByTitle('Close')
Test idpage.getByTestId('checkout')
CSSpage.locator('#user-name'), page.locator('[data-test="error"]')
XPathpage.locator("//td[text()='Jason']/following-sibling::td[2]")
Filterpage.locator('tr').filter({ hasText: 'Jason' })
Chainpage.locator('form').getByRole('button')
Pick one.first(), .last(), .nth(2)
iFramepage.frameLocator('#frame').getByRole('button')

Lessons: locators, CSS and XPath


🖱️ Actions

await page.goto('/inventory.html');
await locator.click();                     // { button: 'right' }, { clickCount: 2 }, { modifiers: ['Shift'] }
await locator.dblclick();
await locator.fill('text');                // clear + set value
await locator.pressSequentially('abc', { delay: 100 });
await locator.press('Enter');              // 'Control+A', 'ArrowDown', 'Tab'
await locator.check();  await locator.uncheck();  await locator.setChecked(true);
await locator.selectOption({ label: 'Option 2' });
await locator.setInputFiles('data/file.pdf');
await locator.hover();
await locator.dragTo(target);
await locator.scrollIntoViewIfNeeded();
await page.keyboard.press('Escape');

Lessons: actions, alerts, popups, iframes, tabs


✅ Assertions

AssertionUse
await expect(page).toHaveURL(/inventory/)Current URL
await expect(page).toHaveTitle('Swag Labs')Page title
await expect(locator).toBeVisible() / toBeHidden()Visibility
await expect(locator).toHaveText('Products')Exact text
await expect(locator).toContainText('locked')Partial text
await expect(locator).toHaveValue('42')Input value
await expect(locator).toHaveCount(6)Number of elements
await expect(locator).toBeChecked() / toBeEnabled() / toBeDisabled()State
await expect(locator).toHaveAttribute('href', '/cart')Attribute
await expect(locator).toHaveClass(/active/)CSS class
await expect(page).toHaveScreenshot('home.png')Visual comparison
await expect(response).toBeOK()API response 2xx
expect.soft(...)Continue after a failure
expect(value).toEqual(obj) / toMatchObject(obj)Plain values (no await)

Lessons: assertions, visual testing


⏳ Waits

await expect(locator).toBeVisible({ timeout: 10_000 });   // preferred
await locator.waitFor({ state: 'hidden' });
await page.waitForURL('**/inventory.html');
await page.waitForLoadState('domcontentloaded');
const resp = page.waitForResponse(r => r.url().includes('/api/') && r.ok());
await button.click(); await resp;                        // start waiting BEFORE the action
const popup = page.waitForEvent('popup');  await link.click();  const newTab = await popup;
await expect.poll(async () => getStatus()).toBe('DONE');
// Avoid: page.waitForTimeout(5000)

Lesson: Playwright waits


🛠️ playwright.config.ts Essentials

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

export default defineConfig({
  testDir: './tests',
  timeout: 30_000,
  expect: { timeout: 5_000 },
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 2 : undefined,
  reporter: [['list'], ['html', { open: 'never' }], ['junit', { outputFile: 'results/junit.xml' }]],
  use: {
    baseURL: process.env.BASE_URL ?? 'https://www.saucedemo.com',
    testIdAttribute: 'data-test',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
    video: 'retain-on-failure',
  },
  projects: [
    { name: 'setup', testMatch: /.*\.setup\.ts/ },
    { name: 'chromium', use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/user.json' }, dependencies: ['setup'] },
    { name: 'mobile', use: { ...devices['iPhone 13'] } },
  ],
});

Lessons: config file, cross-browser, mobile, login sessions


🧩 Fixtures and Page Objects

// Page object
export class LoginPage {
  readonly username: Locator;
  constructor(private readonly page: Page) {
    this.username = page.getByPlaceholder('Username');
  }
  async login(u: string, p: string) { /* fill + click */ }
}

// Custom fixtures
export const test = base.extend<{ loginPage: LoginPage }>({
  loginPage: async ({ page }, use) => { await use(new LoginPage(page)); },
});

// Worker-scoped fixture
account: [async ({}, use, workerInfo) => { await use('user_' + workerInfo.workerIndex); }, { scope: 'worker' }],

Lessons: POM, fixtures, custom fixtures, framework structure


🔌 API Testing and Network

const res = await request.get('/posts', { params: { userId: 1 } });
await request.post('/posts', { data: { title: 'x' } });       // JSON body
await request.post('/login', { form: { email, password } });    // form body
await request.put('/posts/1', { data });  await request.patch('/posts/1', { data });
await request.delete('/posts/1');
expect(res.status()).toBe(200);  const body = await res.json();

await page.route('**/api/items', r => r.fulfill({ json: [] }));              // mock
await page.route('**/api/items', async r => { const resp = await r.fetch(); await r.fulfill({ response: resp, json: { ...(await resp.json()), extra: 1 } }); });
await page.route('**/*.{png,jpg}', r => r.abort());                            // block
page.on('console', m => console.log(m.text()));

Lessons: API testing, network mocking


📸 Debugging, Screenshots and Reports

await page.pause();                                        // open Inspector (headed)
await page.screenshot({ path: 'shot.png', fullPage: true, mask: [locator] });
await locator.screenshot({ path: 'element.png' });
await testInfo.attach('data', { body: JSON.stringify(obj), contentType: 'application/json' });
console.log(testInfo.retry, testInfo.workerIndex, testInfo.tags);

Lessons: debugging, Trace Viewer, screenshots and videos, reporters


🚀 CI in One Minute (GitHub Actions)

- uses: actions/checkout@v4
- uses: actions/setup-node@v4
  with: { node-version: lts/* }
- run: npm ci
- run: npx playwright install --with-deps
- run: npx playwright test
- uses: actions/upload-artifact@v4
  if: always()
  with: { name: playwright-report, path: playwright-report/ }

Lessons: parallel and sharding, GitHub Actions, Jenkins, Docker


🤖 AI Tools

claude mcp add playwright npx @playwright/mcp@latest     # Playwright MCP in Claude Code
npx playwright init-agents --loop=vscode                 # planner, generator, healer agents

Lessons: Playwright MCP, Test Agents


🚫 Top 10 Mistakes to Avoid

  1. Missing await before actions and web-first assertions.
  2. page.waitForTimeout() instead of waiting for a condition.
  3. expect(await locator.textContent()) instead of await expect(locator).toHaveText().
  4. force: true to “fix” covered elements.
  5. Long CSS or absolute XPath selectors.
  6. Tests that depend on each other or share data.
  7. Logging in through the UI in every test instead of storageState.
  8. Selectors and URLs hard-coded inside tests.
  9. Committing test.only, page.pause() or secrets.
  10. Raising retries instead of fixing flaky tests.

❓ FAQ

🤔 Is there a Playwright cheat sheet PDF?

Use your browser’s Print, Save as PDF on this page to keep an offline copy. The page is updated as Playwright evolves.

🤔 What are the most important Playwright commands to remember?

npx playwright test with -g, --grep, --project, --headed, --ui and --debug, plus show-report, show-trace and codegen.

🤔 Which Playwright locators should I memorize first?

getByRole, getByLabel, getByPlaceholder, getByText, getByTestId, and locator() with filter for everything else.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright Interview Questions for Experienced (2, 3 and 5+ Years) with Answers

Experienced Playwright interviews focus on decisions, trade-offs and real problems you have solved. This guide groups the most common questions by experience level, with clear model answers and scenario questions used in SDET and automation lead interviews.

📖 What You’ll Learn: how experienced interviews differ, questions for 2 years (fundamentals in depth), 3 years (framework, data, flakiness, API and UI), 5+ years (strategy, scale, migration, patterns, CI/CD, AI), scenario-based questions, and interview tips.


🎯 How Experienced Interviews Differ

Fresher interviews ask what a feature is. Experienced interviews ask why you chose it, how you scaled it, and what went wrong. Interviewers listen for real decisions, trade-offs and numbers (“we cut the suite from 40 to 9 minutes by…”).

Use this structure for every answer: concept, how you used it, the result. Questions are grouped by the experience level at which they are most commonly asked; prepare one level above your own.

For fundamentals, start with 200 Playwright + TypeScript interview questions.


🟢 2 Years of Experience: Strong Fundamentals

🤔 How does Playwright’s auto-waiting work, and when do you still need explicit waits?

Before each action Playwright checks that the element is attached, visible, stable, enabled and receives events (and editable for fill). Web-first assertions retry until they pass. Explicit waits are still useful for non-element conditions, such as waitForResponse for an API call, waitForURL after navigation, or waitForEvent('popup'). I avoid waitForTimeout completely. See Playwright waits.

🤔 What is the difference between page.locator() and page.$()?

locator() is lazy and re-resolves the element every time it is used, with auto-waiting and strictness. page.$() returns an ElementHandle immediately, which can become stale and does not auto-wait. Locators are the recommended API; element handles are discouraged.

🤔 Which locator strategy do you prefer and why?

User-facing locators first: getByRole with a name, then getByLabel, getByPlaceholder, getByText, then getByTestId. CSS for ids and test attributes, XPath only when I need text plus structure or parent navigation. They are resilient to styling changes and reflect what users see. See CSS and XPath selectors.

🤔 What is strict mode in Playwright?

Actions on a locator fail if it matches more than one element. It prevents clicking the wrong element. I fix violations by making the locator more specific or using filter, not by adding first() everywhere.

🤔 What is the difference between toHaveText and textContent with toBe?

await expect(locator).toHaveText() is a web-first assertion that retries until the text matches. expect(await locator.textContent()).toBe() reads once and fails if the page has not updated yet, which causes flakiness.

🤔 How do you handle a new tab, an alert and an iframe?

New tab: start page.waitForEvent('popup') before the click. Alert: page.once('dialog', d => d.accept()) before the action; Playwright dismisses dialogs by default. Iframe: page.frameLocator() or locator.contentFrame(). See alerts, popups, iframes and tabs.

🤔 What is a browser context and why is it important?

An isolated, incognito-like session with its own cookies and storage. Each test gets a fresh context, which gives isolation without restarting the browser. Contexts also let one test simulate multiple users.

🤔 How do you run a single test, a tag or a browser from the command line?

npx playwright test file.spec.ts:12, --grep @smoke, --project=firefox, and --ui or --debug for investigation. See CLI commands.


🔵 3 Years of Experience: Framework and Reliability

🤔 Describe the architecture of the Playwright framework you built.

Tests in tests/ grouped by feature; src/pages for page objects and components; src/api for API clients; src/fixtures extending test to inject pages, API clients and data; typed data and factories; config per environment through TEST_ENV; a setup project that saves storageState; tags for smoke and regression; HTML and JUnit reporters; GitHub Actions with sharding. Link this to framework structure and give your own numbers.

🤔 Fixtures or hooks: when do you use which?

Hooks for simple, file-specific setup. Fixtures for anything reusable: they combine setup and teardown, run only when requested, can be test- or worker-scoped and pass values directly into tests. In our framework all page objects, API clients and test users come from fixtures. See hooks and custom fixtures.

🤔 How do you avoid logging in through the UI in every test?

A setup project logs in once per role and saves storageState to a file; test projects depend on it and load that state. For multiple roles I use one storage file per role and a fixture or project per role. See save login session.

🤔 How do you handle test data in parallel runs?

Each test creates its own data through the API with unique values (timestamp plus workerIndex) and cleans it up in the same fixture. Shared static data is read-only. Worker-scoped fixtures provide one account per worker when accounts are expensive to create.

🤔 A test is flaky in CI but passes locally. What do you do?

Reproduce with --repeat-each and several workers; enable trace: 'on-first-retry' and inspect the failing attempt in the Trace Viewer: actionability log, DOM snapshot, network and console. Common causes are timing assumptions, shared data, environment differences and overlays. Fix the root cause; retries are only a safety net. See flaky tests and Trace Viewer.

🤔 How do you combine API and UI testing?

API for setup, cleanup and fast verification; UI for user-visible behaviour. For example, create an order through the API, then verify it on the orders page. page.request shares cookies with the page when the API needs the logged-in session. See the hybrid framework project.

🤔 When do you mock network calls?

For error, empty and edge states, unreliable third-party services and features whose backend is not ready. Critical end-to-end journeys run against real services. I use page.route with fulfill, route.fetch to modify real responses, and HAR replay for stable fixtures. See network mocking.

🤔 How do you run tests across environments?

Base URLs per environment in config, selected by an environment variable; secrets from CI secret stores; .env locally with .env.example committed. Projects or separate config files for API and UI.

🤔 How do you implement visual testing, and how do you keep it stable?

toHaveScreenshot on key pages and components, with masks for dynamic content, small tolerances and baselines generated in the same Docker image as CI. Visual tests run in one browser project. See visual testing.


🟠 5+ Years of Experience: Architecture, Scale and Strategy

🤔 How would you design a test automation strategy for a new product?

Start from risk and the test pyramid: most checks at unit and API level, a focused set of end-to-end journeys in Playwright, visual checks for key screens, and contract tests between services. Define quality gates (smoke on every PR, full regression nightly), environments and data strategy, ownership, and metrics such as pipeline time, flaky rate and escaped defects.

🤔 How do you scale a suite of 3,000 Playwright tests?

fullyParallel plus sharding across CI machines with merged blob reports; login and data setup through API and storage state; tag-based selection so PRs run only relevant suites; trace on retry only; resource blocking where safe; regular removal of low-value or duplicate tests; and monitoring of the slowest tests. See parallel execution and sharding.

🤔 How do you measure and reduce flakiness at team level?

Track flaky tests from CI reports over time, fail release pipelines on flaky tests (--fail-on-flaky-tests), quarantine with a tag and a ticket, and require a root-cause fix within a set time. Review new tests with --repeat-each before merging.

🤔 How do you migrate a Selenium suite to Playwright?

Assess value first; do not port everything. Build the new framework skeleton, start with smoke journeys, run both suites in parallel for a period, migrate feature by feature with a concept map (waits to web-first assertions, switchTo to frameLocator and popup events), and retire Selenium tests as coverage moves. Measure execution time and flakiness before and after. See Playwright vs Selenium vs Cypress.

🤔 Which design patterns do you use in a Playwright framework?

Page Object and component objects, fixtures as dependency injection, factory and builder for test data, strategy for environment-specific behaviour, and facades for multi-step business flows. SOLID principles keep classes small and replaceable. See design patterns and SOLID.

🤔 How do you make the framework maintainable for a large team?

Clear layering and naming conventions, ESLint with the Playwright plugin, type checking in CI, code review checklists, documentation and examples, shared fixtures owned by the platform team, and pairing for onboarding.

🤔 How do you integrate Playwright into CI/CD and release decisions?

PR gate with smoke tests and type checks, nightly cross-browser regression, post-deployment smoke against each environment, reports and traces as artifacts, JUnit for dashboards, and notifications through a custom reporter. A failed gate blocks the merge or deployment. See GitHub Actions and Jenkins.

🤔 How are you using AI in test automation?

Playwright MCP for exploration and drafting, and Playwright Test Agents to plan, generate and heal tests, always with human review of plans, generated code and healed diffs. AI speeds up authoring and maintenance; deterministic tests in CI remain the source of truth. See Playwright MCP and Test Agents.


🧩 Scenario-Based Questions

🤔 The login page takes 8 seconds in the test environment and 200 tests log in through the UI. What do you change?

Log in once per role in a setup project and reuse storageState, or create sessions through an API. That removes 200 slow UI logins and their flakiness.

🤔 A button is sometimes covered by a toast notification and the click fails. How do you fix it?

Wait for the toast to disappear (await expect(toast).toBeHidden()) or close it, then click. Do not use force: true, which hides real user-facing problems.

🤔 Your suite takes 45 minutes on one CI machine. The team wants feedback in under 10. What is your plan?

Measure first (slowest tests, setup time). Then: fullyParallel, 4 shards with merged reports, API-based setup, storage state, smoke subset on PRs and full suite nightly, and remove redundant UI tests already covered at API level.

🤔 A healer agent “fixed” a failing test by changing the expected total. What do you do?

Reject the change and investigate: a changed expected value may hide a real bug. Healed changes are reviewed like any code change; skipped or changed assertions require confirmation from the product or development team.

🤔 Tests pass alone but fail when run in parallel. What is the likely cause?

Shared state: the same user, cart or record used by several tests. Make data unique per test or per worker and remove dependencies between tests.


💡 Tips for the Interview

  • Prepare two stories: one about improving speed, one about fixing flakiness, each with numbers.
  • Be ready to share your screen and walk through your framework; a public project from Project 2 or Project 3 is ideal.
  • For lead roles, also review QA automation lead interview questions and manager round questions.
  • Practise writing a test live, without an IDE’s autocomplete, for a simple login and an API call.

🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright Practice Assignments: Module-wise Exercises for Beginners to Advanced

Reading is not enough: you learn Playwright by building. This page gives you one checkpoint challenge per module of the course, using free practice sites, so you can prove your skills step by step from your first test to a CI-ready framework.

📖 What You’ll Learn: how to use the checkpoints, the practice applications, a challenge for each of the 15 modules (setup, JavaScript, TypeScript, locators, assertions, organization, data, network, API, framework design, debugging, CI/CD, AI testing, projects and interview readiness).


🏋️ How to Use This Page

Every lesson in the Playwright Tutorial with TypeScript ends with its own assignment. This page adds one module checkpoint per module: a slightly bigger challenge that combines the lessons of that module. Complete it before moving on.

Rules for every checkpoint:

  • Write the solution in TypeScript with Playwright Test.
  • Every test must pass three times in a row: npx playwright test --repeat-each=3.
  • No waitForTimeout, no force: true, no selectors inside tests from Module 10 onward.
  • Commit each checkpoint to Git with a clear message, so your repository shows your progress.

Practice applications used: https://www.saucedemo.com, https://the-internet.herokuapp.com, https://demo.playwright.dev/api-mocking, https://jsonplaceholder.typicode.com, https://automationexercise.com and the SQA Tools practice pages.

LevelModulesBadge
🟢 Beginner1 to 5Playwright Practitioner
🔵 Intermediate6 to 9Playwright Engineer
🟠 Advanced10 to 13Playwright Architect
🟣 Career14 to 15Interview Ready

🟢 Module 1 Checkpoint: Getting Started

Lessons: What Is Playwright, Install, First Test, Config, CLI

  1. Create a new TypeScript project with npm init playwright@latest and remove the example test.
  2. Configure baseURL for Sauce Demo, list plus html reporters, screenshots on failure and Chromium plus Firefox projects.
  3. Write three login tests (valid, locked out, empty form) in one describe block.
  4. Add npm scripts test, test:headed, test:ui and report.
  5. Write a short README explaining how to install and run the project.

🟢 Module 2 Checkpoint: JavaScript Essentials

Lessons: Variables to Promises and Async/Await

  1. Write a function calculateCartTotal(items) that takes an array of { name, price, qty } objects and returns the total rounded to two decimals.
  2. Write a function that returns the most expensive item using reduce.
  3. Write an async function fetchUser(id) that calls https://jsonplaceholder.typicode.com/users/<id> with fetch and handles errors with try/catch.
  4. Fetch users 1 to 5 in parallel with Promise.all and print their names.

🟢 Module 3 Checkpoint: TypeScript for Playwright

Lessons: TypeScript Variables to TypeScript for Playwright

  1. Create interfaces Product and CartItem, and a type SortOption = 'az' | 'za' | 'lohi' | 'hilo'.
  2. Create a generic class Repository<T extends { id: number }> with add, findById and all methods.
  3. Rewrite calculateCartTotal from Module 2 with full types.
  4. Add tsconfig.json with strict: true and make npx tsc --noEmit pass.

🟢 Module 4 Checkpoint: Locators and Interactions

Lessons: Locators, CSS and XPath, Actions, Codegen, Alerts, Frames, Tabs, Web Tables, Downloads

On the-internet.herokuapp.com:

  1. Accept, dismiss and answer the three JavaScript dialogs on /javascript_alerts.
  2. Open the new window on /windows and assert its heading, then return to the first tab.
  3. Read the text of the middle frame on /nested_frames.
  4. On /tables, find the person with the highest amount due in #table1 by reading all rows.
  5. Select both options on /dropdown, tick both boxes on /checkboxes, and upload a file on /upload.

🟢 Module 5 Checkpoint: Assertions, Waits and Screenshots

Lessons: Assertions, Waits, Screenshots and Videos, Visual Testing

  1. On /dynamic_loading/1 of the-internet, click Start and assert “Hello World!” appears, using only auto-waiting and web-first assertions.
  2. Use expect.soft to check five product prices on Sauce Demo in one test.
  3. Configure screenshots and videos on failure and attach a custom screenshot with testInfo.attach.
  4. Create visual baselines for the Sauce Demo login page (full page and .login-box element), masking the credentials panel.

🔵 Module 6 Checkpoint: Organizing Tests

Lessons: Hooks, Tags and grep, Annotations, Fixtures, Custom Fixtures, Retries and Flaky Tests

  1. Replace every beforeEach login in your Sauce Demo suite with a custom loggedInPage fixture.
  2. Tag tests @smoke and @regression and add npm scripts for each.
  3. Mark one test test.fixme with a reason and one test.slow.
  4. Configure retries for CI only with trace: 'on-first-retry', write a deliberately flaky test, and find it under Flaky in the report. Then delete it.

🔵 Module 7 Checkpoint: Test Data, Configuration and Cross-Browser

Lessons: Parameterized Tests, JSON, CSV, .env, Multiple Configs, Cross-Browser, Mobile

  1. Move all login test data into test-data/logins.json and generate one test per row.
  2. Read the Sauce Demo password from a .env file and add .env.example.
  3. Run the suite in Chromium, Firefox, WebKit, branded Chrome and a Pixel 5 project.
  4. Add responsive tests for 375, 768 and 1440 px widths.

🔵 Module 8 Checkpoint: Authentication and Network

Lessons: Login Sessions, Network Mocking, Passkeys

  1. Add a setup project that logs in to Sauce Demo once and saves storageState; make all inventory tests reuse it.
  2. On demo.playwright.dev/api-mocking, mock the fruits API with your own list, then simulate an empty list and a 500 error.
  3. Block all images on Sauce Demo and measure the time difference of your suite.

🔵 Module 9 Checkpoint: API Testing

Lessons: API Testing, API with POM

  1. Create an api project for JSONPlaceholder with baseURL.
  2. Write a PostsApi class with typed list, get, create, update and delete methods.
  3. Write a full CRUD test suite (at least 8 tests) using the class.
  4. Add one negative test (/posts/0 returns 404).

🟠 Module 10 Checkpoint: Framework Design

Lessons: POM, Folder Structure, Design Patterns, SOLID, BDD, BDD Framework, Enterprise Framework

  1. Restructure your Sauce Demo suite into src/ and tests/ with page objects, a HeaderComponent and fixtures.
  2. Add path aliases and an environments.ts file selected by TEST_ENV.
  3. Add ESLint with eslint-plugin-playwright and fix all warnings.
  4. Write two features in Gherkin (login, checkout) using the BDD approach from Module 10.

🟠 Module 11 Checkpoint: Debugging and Reporting

Lessons: Debugging, Trace Viewer, Reporters, Allure

  1. Break a locator, then diagnose it three ways: error call log, --debug Inspector, and Trace Viewer. Write a short note on which was fastest.
  2. Wrap your checkout test in test.step blocks and view them in the trace and HTML report.
  3. Configure list, html, junit and Allure reporters together.
  4. Write a custom reporter that prints the five slowest tests.

🟠 Module 12 Checkpoint: Parallel Execution and CI/CD

Lessons: Parallel and Sharding, GitHub Actions, Jenkins, Docker and Kubernetes

  1. Enable fullyParallel and make the whole suite pass with --workers=4 --repeat-each=3.
  2. Push the project to GitHub with a workflow that runs smoke tests on pull requests and the full suite nightly.
  3. Shard the nightly run into 3 jobs with a merged HTML report.
  4. Run the suite locally inside the official Playwright Docker image.

🟠 Module 13 Checkpoint: AI-Powered Testing

Lessons: Playwright MCP, Test Agents, AI Tools for QA

  1. Install Playwright MCP in your AI client and use it to explore the Sauce Demo checkout flow.
  2. Run npx playwright init-agents, write a seed test, and generate a test plan for sorting and the cart.
  3. Generate tests from the plan, review them, and refactor them into your page objects.
  4. Write a one-page reflection: what the agents did well, what you had to fix, and where human review was essential.

🟣 Module 14 Checkpoint: Projects

Complete Project 1, Project 2: E-commerce Framework and Project 3: API + UI Hybrid Framework, and publish at least Projects 2 and 3 on GitHub with a README, a passing CI badge and a short “design decisions” section.


🟣 Module 15 Checkpoint: Interview Readiness

  1. Answer the 200 Playwright + TypeScript questions out loud, timing yourself; mark the ones you could not explain.
  2. Prepare a 3-minute walkthrough of your Project 2 or 3 framework.
  3. Practise the scenario questions in interview questions for experienced.

❓ FAQ

🤔 Where can I practise Playwright automation for free?

Use the free demo sites listed on this page (Sauce Demo, the-internet, Playwright’s API-mocking demo, JSONPlaceholder and Automation Exercise) and the SQA Tools practice pages, together with the module checkpoints.

🤔 Are solutions provided for these assignments?

Each linked lesson contains the code and techniques you need. Compare your work with the examples in the lessons and the two framework projects.

🤔 How long does it take to complete all assignments?

With 1 to 2 hours a day, most learners finish the module checkpoints and projects in about 2 to 3 months.

🤔 Do I need to finish every checkpoint before the projects?

Finish at least Modules 1 to 10 before Project 2, and Modules 1 to 12 before Project 3.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright Project: API + UI Hybrid Framework with CI (TypeScript)

In this capstone project you will combine API and UI automation like a senior SDET: an API client layer, fixtures that create and clean up test users through the API, hybrid tests that verify in the browser, and a CI pipeline with separate API and UI jobs.

📖 What You’ll Learn: the practice API and its quirks, project structure and config with API and UI projects, a test data factory, a typed API client, setup and teardown fixtures, API tests, hybrid API-to-UI tests, a CI pipeline with dependent jobs, an acceptance checklist and stretch goals.


🎯 Project Brief

Real-world frameworks rarely test only the UI. Senior automation engineers use the API for fast, reliable setup and cleanup, the UI for what users actually see, and run everything in CI. In this capstone you will build exactly that.

Application under test: https://automationexercise.com, a free practice e-commerce site that offers both a web UI and a documented REST API (see its “API Testing” page).

Time needed: 10 to 15 hours. Complete Project 2 first.


🔌 The API You Will Use

EndpointMethodParameters (form data)Expected
/api/productsListGETnoneresponseCode 200 and a products array
/api/createAccountPOSTname, email, password, title, birth_date, birth_month, birth_year, firstname, lastname, company, address1, address2, country, zipcode, state, city, mobile_numberresponseCode 201, “User created!”
/api/verifyLoginPOSTemail, password200 “User exists!” or 404 “User not found!”
/api/getUserDetailByEmailGETemail (query)responseCode 200 with user details
/api/deleteAccountDELETEemail, passwordresponseCode 200, “Account deleted!”

⚠️ Common mistake: This API returns HTTP 200 for almost every call and puts the real result in a responseCode field in the JSON body. Always assert both the HTTP status and responseCode. This is a common pattern in real legacy APIs, and a classic interview question.


📋 Requirements

  • An API client layer with typed methods for each endpoint (API testing, API with POM).
  • A newUser fixture that creates a unique account through the API before a test and deletes it afterwards.
  • Hybrid tests: create a user via API, then log in and verify through the UI.
  • Cross-checks: data shown in the UI matches the API.
  • Pure API tests tagged @api and UI tests tagged @ui, in separate projects.
  • CI pipeline with separate API and UI jobs and the HTML report as an artifact (GitHub Actions).

📁 Step 1: Structure

hybrid-framework/
├── src/
│   ├── api/
│   │   └── AccountApi.ts
│   ├── pages/
│   │   ├── LoginPage.ts
│   │   └── components/Header.ts
│   ├── fixtures/index.ts
│   └── data/userFactory.ts
├── tests/
│   ├── api/products.api.spec.ts
│   ├── api/account.api.spec.ts
│   └── ui/login.hybrid.spec.ts
├── .github/workflows/ci.yml
└── playwright.config.ts

⚙️ Step 2: Config with API and UI Projects

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

export default defineConfig({
  testDir: './tests',
  fullyParallel: true,
  retries: process.env.CI ? 2 : 0,
  reporter: [['list'], ['html', { open: 'never' }]],
  use: {
    baseURL: 'https://automationexercise.com',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
  },
  projects: [
    { name: 'api', testMatch: /.*\.api\.spec\.ts/ },
    { name: 'ui',  testMatch: /.*\.hybrid\.spec\.ts/, use: { ...devices['Desktop Chrome'] } },
  ],
});

🏭 Step 3: Unique Test Data with a Factory

Every test needs its own user so tests can run in parallel without clashing (parallel execution):

// src/data/userFactory.ts
export interface NewUser {
  name: string; email: string; password: string;
  title: string; birth_date: string; birth_month: string; birth_year: string;
  firstname: string; lastname: string; company: string;
  address1: string; address2: string; country: string;
  zipcode: string; state: string; city: string; mobile_number: string;
}

export function buildUser(overrides: Partial<NewUser> = {}): NewUser {
  const id = Date.now() + '_' + Math.floor(Math.random() * 10000);
  return {
    name: 'QA User ' + id,
    email: 'qa_' + id + '@example.com',
    password: 'Test@' + id,
    title: 'Mr', birth_date: '10', birth_month: '5', birth_year: '1995',
    firstname: 'QA', lastname: 'Tester', company: 'SQA Tools',
    address1: '1 Test Street', address2: 'Floor 2', country: 'India',
    zipcode: '411001', state: 'Maharashtra', city: 'Pune', mobile_number: '9999999999',
    ...overrides,
  };
}

This is the Builder/Factory idea from design patterns, in its simplest form.


🔌 Step 4: The API Client

// src/api/AccountApi.ts
import { APIRequestContext, APIResponse, expect } from '@playwright/test';
import { NewUser } from '../data/userFactory';

interface ApiResult { responseCode: number; message?: string; [key: string]: unknown }

export class AccountApi {
  constructor(private readonly request: APIRequestContext) {}

  private async parse(response: APIResponse): Promise<ApiResult> {
    expect(response.status(), 'HTTP status').toBe(200);
    return response.json();
  }

  async productsList(): Promise<ApiResult> {
    return this.parse(await this.request.get('/api/productsList'));
  }

  async createAccount(user: NewUser): Promise<ApiResult> {
    return this.parse(await this.request.post('/api/createAccount', { form: { ...user } }));
  }

  async verifyLogin(email: string, password: string): Promise<ApiResult> {
    return this.parse(await this.request.post('/api/verifyLogin', { form: { email, password } }));
  }

  async getUserByEmail(email: string): Promise<ApiResult> {
    return this.parse(await this.request.get('/api/getUserDetailByEmail', { params: { email } }));
  }

  async deleteAccount(email: string, password: string): Promise<ApiResult> {
    return this.parse(await this.request.delete('/api/deleteAccount', { form: { email, password } }));
  }
}

🧩 Step 5: Fixtures: Setup and Cleanup in One Place

The newUser fixture creates the account before the test and deletes it after, even if the test fails (custom fixtures):

// src/fixtures/index.ts
import { test as base, expect } from '@playwright/test';
import { AccountApi } from '../api/AccountApi';
import { buildUser, NewUser } from '../data/userFactory';
import { LoginPage } from '../pages/LoginPage';

type Fixtures = { accountApi: AccountApi; newUser: NewUser; loginPage: LoginPage };

export const test = base.extend<Fixtures>({
  accountApi: async ({ request }, use) => {
    await use(new AccountApi(request));
  },

  newUser: async ({ accountApi }, use) => {
    const user = buildUser();
    const created = await accountApi.createAccount(user);
    expect(created.responseCode, 'create account').toBe(201);

    await use(user);                                  // the test runs here

    const deleted = await accountApi.deleteAccount(user.email, user.password);
    expect(deleted.responseCode, 'delete account').toBe(200);
  },

  loginPage: async ({ page }, use) => {
    await use(new LoginPage(page));
  },
});
export { expect };
// src/pages/LoginPage.ts
import { Page, Locator } from '@playwright/test';

export class LoginPage {
  readonly email: Locator;
  readonly password: Locator;
  readonly submit: Locator;

  constructor(private readonly page: Page) {
    this.email = page.locator('[data-qa="login-email"]');
    this.password = page.locator('[data-qa="login-password"]');
    this.submit = page.locator('[data-qa="login-button"]');
  }

  async open() { await this.page.goto('/login'); }

  async login(email: string, password: string) {
    await this.email.fill(email);
    await this.password.fill(password);
    await this.submit.click();
  }
}

🧪 Step 6: API Tests

// tests/api/products.api.spec.ts
import { test, expect } from '../../src/fixtures';

test('products list returns products with required fields', { tag: '@api' }, async ({ accountApi }) => {
  const result = await accountApi.productsList();
  expect(result.responseCode).toBe(200);

  const products = result.products as { id: number; name: string; price: string; brand: string }[];
  expect(products.length).toBeGreaterThan(0);
  for (const p of products) {
    expect(p).toMatchObject({ id: expect.any(Number), name: expect.any(String), price: expect.any(String) });
  }
});
// tests/api/account.api.spec.ts
import { test, expect } from '../../src/fixtures';

test('a new user can be verified by login API', { tag: '@api' }, async ({ accountApi, newUser }) => {
  const result = await accountApi.verifyLogin(newUser.email, newUser.password);
  expect(result.responseCode).toBe(200);
  expect(result.message).toBe('User exists!');
});

test('unknown user is not found', { tag: '@api' }, async ({ accountApi }) => {
  const result = await accountApi.verifyLogin('nobody_' + Date.now() + '@example.com', 'wrong');
  expect(result.responseCode).toBe(404);
});

🔗 Step 7: Hybrid Tests (API Setup, UI Verification)

// tests/ui/login.hybrid.spec.ts
import { test, expect } from '../../src/fixtures';

test('user created via API can log in through the UI', { tag: '@ui' }, async ({ page, newUser, loginPage }) => {
  await loginPage.open();
  await loginPage.login(newUser.email, newUser.password);
  await expect(page.getByText('Logged in as ' + newUser.name)).toBeVisible();
});

test('wrong password shows an error', { tag: '@ui' }, async ({ page, newUser, loginPage }) => {
  await loginPage.open();
  await loginPage.login(newUser.email, 'wrong-password');
  await expect(page.getByText('Your email or password is incorrect!')).toBeVisible();
});

Creating the user through the UI would take a long sign-up form and several pages per test. Through the API it takes one request, which makes UI tests faster and far less flaky.

📝 Note: Public practice sites sometimes show cookie-consent or advertising overlays. If one covers the form in your region, close it in a beforeEach or block third-party ad requests with page.route (network mocking).


🚀 Step 8: CI with Separate API and UI Jobs

name: Hybrid Framework CI
on: [push, pull_request]

jobs:
  api-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: lts/* }
      - run: npm ci
      - run: npx playwright test --project=api

  ui-tests:
    needs: api-tests                 # run UI only if the API is healthy
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: lts/* }
      - run: npm ci
      - run: npx playwright install --with-deps chromium
      - run: npx playwright test --project=ui
      - uses: actions/upload-artifact@v4
        if: ${{ !cancelled() }}
        with:
          name: playwright-report
          path: playwright-report/

API tests need no browser, so that job is very fast. If the API is down, the UI job does not even start.


✅ Acceptance Checklist

  • [ ] AccountApi covers all five endpoints with typed results
  • [ ] Every test that needs a user gets a unique one from the newUser fixture
  • [ ] Accounts are deleted after each test, even on failure
  • [ ] At least 6 API tests and 4 hybrid UI tests
  • [ ] Both status() and responseCode are asserted
  • [ ] Suite passes with --repeat-each=3 --workers=4
  • [ ] CI runs API and UI jobs; the HTML report is uploaded

🏅 Evaluation Rubric

CriterionWeight
API layer design and assertions25%
Fixture design (setup and teardown, isolation)25%
Hybrid test value (faster, more reliable than UI-only)20%
Reliability in parallel and CI15%
Code quality and documentation (README)15%

🚀 Stretch Goals

  • Cross-check: search a product in the UI and assert its price matches productsList.
  • Add getUserByEmail assertions after an account update with PUT /api/updateAccount.
  • Validate the products response against a JSON schema.
  • Add a nightly scheduled run and a Slack or Teams notification using a custom reporter.
  • Run the UI job inside the official Playwright Docker image (Docker).

❓ FAQ

🤔 What is a hybrid API and UI test?

A test that uses API calls for setup or verification and the browser for the user-facing part, for example creating a user through the API and then logging in through the UI.

🤔 Why use the API for test setup in Playwright?

API calls are much faster and more stable than clicking through forms, so tests spend their time verifying behaviour instead of preparing data.

🤔 How do I clean up test data in Playwright?

Put creation and deletion in one fixture: create before use() and delete after it. The cleanup runs even when the test fails.

🤔 Why assert both HTTP status and responseCode?

Some APIs always return HTTP 200 and report errors inside the body. Checking only the HTTP status would let real failures pass.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright Project: Build an E-commerce E2E Framework with TypeScript

Time to build something real. In this project you will create a complete Playwright + TypeScript framework for an online store, from requirements and folder structure to page objects, fixtures, data-driven tests, cross-browser runs and a CI pipeline.

📖 What You’ll Learn: how to turn requirements into a test scope, project configuration with setup and browser projects, logging in once with storageState, page objects for inventory, cart and checkout, fixtures and typed test data, smoke and regression tests, CI, an acceptance checklist and an evaluation rubric.


🎯 Project Brief

You are the automation engineer for Swag Labs (https://www.saucedemo.com), an online store. Build a production-style Playwright + TypeScript framework that covers the store’s critical journeys and runs automatically in CI.

This project brings together everything from Modules 1 to 12. Work through it step by step; each step links back to the lesson that teaches the skill.

Time needed: 8 to 12 hours, spread over a week.


📋 Requirements

Functional coverage

AreaScenarios
LoginValid login, locked-out user, wrong password, empty fields (data-driven)
InventoryProduct count, sorting A-Z, Z-A, price low-high, price high-low
CartAdd one, add several, remove, badge count, cart page contents
CheckoutRequired-field validation, price summary (item total, tax, total), order completion
SessionLogout, protected pages redirect to login when logged out

Technical requirements


📁 Step 1: Create the Project and Folders

mkdir swaglabs-playwright && cd swaglabs-playwright
npm init playwright@latest
swaglabs-playwright/
├── .github/workflows/playwright.yml
├── src/
│   ├── pages/
│   │   ├── BasePage.ts
│   │   ├── LoginPage.ts
│   │   ├── InventoryPage.ts
│   │   ├── CartPage.ts
│   │   └── CheckoutPage.ts
│   ├── fixtures/index.ts
│   └── data/
│       ├── users.ts
│       └── checkout.ts
├── tests/
│   ├── auth.setup.ts
│   ├── login.spec.ts
│   ├── inventory.spec.ts
│   ├── cart.spec.ts
│   └── checkout.spec.ts
├── playwright/.auth/          # add to .gitignore
└── playwright.config.ts

The layout follows framework folder structure and best practices.


⚙️ Step 2: Configuration

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

const authFile = 'playwright/.auth/standard.json';

export default defineConfig({
  testDir: './tests',
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 2 : undefined,
  reporter: process.env.CI ? [['dot'], ['github'], ['html', { open: 'never' }]] : [['list'], ['html', { open: 'on-failure' }]],
  use: {
    baseURL: 'https://www.saucedemo.com',
    testIdAttribute: 'data-test',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
  },
  projects: [
    { name: 'setup', testMatch: /.*\.setup\.ts/ },
    { name: 'chromium', use: { ...devices['Desktop Chrome'], storageState: authFile }, dependencies: ['setup'] },
    { name: 'firefox',  use: { ...devices['Desktop Firefox'], storageState: authFile }, dependencies: ['setup'] },
    { name: 'mobile',   use: { ...devices['Pixel 5'], storageState: authFile }, dependencies: ['setup'], grep: /@smoke/ },
  ],
});

📝 Note: Login tests must start logged out. In login.spec.ts add test.use({ storageState: { cookies: [], origins: [] } }) to ignore the saved session.


🔐 Step 3: Log In Once (Setup Project)

// tests/auth.setup.ts
import { test as setup, expect } from '@playwright/test';

const authFile = 'playwright/.auth/standard.json';

setup('authenticate as standard user', async ({ page }) => {
  await page.goto('/');
  await page.getByPlaceholder('Username').fill('standard_user');
  await page.getByPlaceholder('Password').fill(process.env.SAUCE_PASSWORD ?? 'secret_sauce');
  await page.getByRole('button', { name: 'Login' }).click();
  await expect(page).toHaveURL(/inventory/);
  await page.context().storageState({ path: authFile });
});

🧱 Step 4: Page Objects

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

export abstract class BasePage {
  readonly cartBadge: Locator;
  readonly cartLink: Locator;

  constructor(protected readonly page: Page) {
    this.cartBadge = page.locator('.shopping_cart_badge');
    this.cartLink = page.locator('.shopping_cart_link');
  }

  protected abstract readonly path: string;

  async open(): Promise<void> {
    await this.page.goto(this.path);
  }
}
// src/pages/InventoryPage.ts
import { Page, Locator } from '@playwright/test';
import { BasePage } from './BasePage';

export type SortOption = 'az' | 'za' | 'lohi' | 'hilo';

export class InventoryPage extends BasePage {
  protected readonly path = '/inventory.html';
  readonly title: Locator;
  readonly items: Locator;
  readonly sortSelect: Locator;

  constructor(page: Page) {
    super(page);
    this.title = page.locator('.title');
    this.items = page.locator('.inventory_item');
    this.sortSelect = page.getByTestId('product-sort-container');
  }

  item(name: string): Locator {
    return this.items.filter({ hasText: name });
  }

  async addToCart(...names: string[]): Promise<void> {
    for (const name of names) {
      await this.item(name).getByRole('button', { name: 'Add to cart' }).click();
    }
  }

  async sortBy(option: SortOption): Promise<void> {
    await this.sortSelect.selectOption(option);
  }

  async names(): Promise<string[]> {
    return this.page.locator('.inventory_item_name').allTextContents();
  }

  async prices(): Promise<number[]> {
    const texts = await this.page.locator('.inventory_item_price').allTextContents();
    return texts.map(t => Number(t.replace('$', '')));
  }
}
// src/pages/CartPage.ts
import { Page, Locator } from '@playwright/test';
import { BasePage } from './BasePage';

export class CartPage extends BasePage {
  protected readonly path = '/cart.html';
  readonly items: Locator;
  readonly checkoutButton: Locator;

  constructor(page: Page) {
    super(page);
    this.items = page.locator('.cart_item');
    this.checkoutButton = page.getByTestId('checkout');
  }

  async remove(name: string): Promise<void> {
    await this.items.filter({ hasText: name }).getByRole('button', { name: 'Remove' }).click();
  }
}
// src/pages/CheckoutPage.ts
import { Page, Locator } from '@playwright/test';
import { BasePage } from './BasePage';

export interface CustomerInfo { firstName: string; lastName: string; postalCode: string }

export class CheckoutPage extends BasePage {
  protected readonly path = '/checkout-step-one.html';
  readonly error: Locator;
  readonly itemTotal: Locator;
  readonly tax: Locator;
  readonly total: Locator;
  readonly completeHeader: Locator;

  constructor(page: Page) {
    super(page);
    this.error = page.getByTestId('error');
    this.itemTotal = page.locator('.summary_subtotal_label');
    this.tax = page.locator('.summary_tax_label');
    this.total = page.locator('.summary_total_label');
    this.completeHeader = page.locator('.complete-header');
  }

  async fillInformation(info: CustomerInfo): Promise<void> {
    await this.page.getByTestId('firstName').fill(info.firstName);
    await this.page.getByTestId('lastName').fill(info.lastName);
    await this.page.getByTestId('postalCode').fill(info.postalCode);
    await this.page.getByTestId('continue').click();
  }

  async finish(): Promise<void> {
    await this.page.getByTestId('finish').click();
  }
}

Write LoginPage yourself, following the example in the framework structure lesson.


🧩 Step 5: Fixtures and Test Data

// src/fixtures/index.ts
import { test as base } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';
import { InventoryPage } from '../pages/InventoryPage';
import { CartPage } from '../pages/CartPage';
import { CheckoutPage } from '../pages/CheckoutPage';

type Pages = { loginPage: LoginPage; inventoryPage: InventoryPage; cartPage: CartPage; checkoutPage: CheckoutPage };

export const test = base.extend<Pages>({
  loginPage:     async ({ page }, use) => { await use(new LoginPage(page)); },
  inventoryPage: async ({ page }, use) => { await use(new InventoryPage(page)); },
  cartPage:      async ({ page }, use) => { await use(new CartPage(page)); },
  checkoutPage:  async ({ page }, use) => { await use(new CheckoutPage(page)); },
});
export { expect } from '@playwright/test';
// src/data/checkout.ts
import { CustomerInfo } from '../pages/CheckoutPage';

export const validCustomer: CustomerInfo = { firstName: 'Asha', lastName: 'Verma', postalCode: '411001' };

export const missingFieldCases: { name: string; info: CustomerInfo; error: string }[] = [
  { name: 'first name', info: { firstName: '', lastName: 'Verma', postalCode: '411001' }, error: 'First Name is required' },
  { name: 'last name',  info: { firstName: 'Asha', lastName: '', postalCode: '411001' }, error: 'Last Name is required' },
  { name: 'postal code', info: { firstName: 'Asha', lastName: 'Verma', postalCode: '' }, error: 'Postal Code is required' },
];

🧪 Step 6: Tests

// tests/inventory.spec.ts
import { test, expect } from '../src/fixtures';

test.beforeEach(async ({ inventoryPage }) => {
  await inventoryPage.open();
});

test('shows six products', { tag: '@smoke' }, async ({ inventoryPage }) => {
  await expect(inventoryPage.items).toHaveCount(6);
});

test('sorts by price low to high', { tag: '@regression' }, async ({ inventoryPage }) => {
  await inventoryPage.sortBy('lohi');
  const prices = await inventoryPage.prices();
  expect(prices).toEqual([...prices].sort((a, b) => a - b));
});

test('sorts by name Z to A', { tag: '@regression' }, async ({ inventoryPage }) => {
  await inventoryPage.sortBy('za');
  const names = await inventoryPage.names();
  expect(names).toEqual([...names].sort().reverse());
});
// tests/checkout.spec.ts
import { test, expect } from '../src/fixtures';
import { validCustomer, missingFieldCases } from '../src/data/checkout';

test.beforeEach(async ({ inventoryPage, cartPage }) => {
  await inventoryPage.open();
  await inventoryPage.addToCart('Sauce Labs Backpack');
  await inventoryPage.cartLink.click();
  await cartPage.checkoutButton.click();
});

test('complete an order with correct totals', { tag: ['@smoke', '@regression'] }, async ({ checkoutPage }) => {
  await checkoutPage.fillInformation(validCustomer);
  await expect(checkoutPage.itemTotal).toHaveText('Item total: $29.99');
  await expect(checkoutPage.tax).toHaveText('Tax: $2.40');
  await expect(checkoutPage.total).toHaveText('Total: $32.39');
  await checkoutPage.finish();
  await expect(checkoutPage.completeHeader).toHaveText('Thank you for your order!');
});

for (const c of missingFieldCases) {
  test('checkout requires ' + c.name, { tag: '@regression' }, async ({ checkoutPage }) => {
    await checkoutPage.fillInformation(c.info);
    await expect(checkoutPage.error).toContainText(c.error);
  });
}

Write login.spec.ts (data-driven, logged out) and cart.spec.ts (add several, remove, badge) yourself.

💡 Tip: Each test adds its own products after the saved login, so tests never depend on each other and can run fully in parallel (parallel execution).


🚀 Step 7: Continuous Integration

Use the workflow from Run Playwright tests in GitHub Actions. Add playwright/.auth/ to .gitignore, push to GitHub and confirm that the pipeline runs, uploads the HTML report, and fails if you break a test.


✅ Acceptance Checklist

  • [ ] At least 20 tests across login, inventory, cart, checkout and session
  • [ ] No selectors or URLs inside test files
  • [ ] Login runs once per run (setup project)
  • [ ] Data-driven login and checkout validation tests
  • [ ] @smoke suite runs in under 2 minutes
  • [ ] Passes in Chromium, Firefox and the mobile project
  • [ ] Stable with --repeat-each=5
  • [ ] CI pipeline green, HTML report and traces available

🏅 Evaluation Rubric

CriterionWeight
Coverage of the required scenarios25%
Framework design (POM, fixtures, data, structure)25%
Reliability (no flaky tests, no hard waits)20%
Readability (naming, test titles, tags)15%
CI and reporting15%

🚀 Stretch Goals

  • Visual tests for the inventory and cart pages (visual testing).
  • Tests for problem_user that document the known UI bugs (use test.fail()).
  • Shard the pipeline into two jobs with a merged report.
  • Ask the Playwright Test Agents to propose missing scenarios and compare with your plan.

❓ FAQ

🤔 What is a good Playwright project for a portfolio?

An e-commerce framework like this one: page objects, fixtures, data-driven tests, cross-browser and mobile projects, a setup project for login, and a green CI pipeline on GitHub.

🤔 Should I put this project on GitHub?

Yes. A public repository with a clear README, a passing Actions badge and a short description of the design decisions is strong evidence in interviews.

🤔 Why use storageState instead of logging in before each test?

Logging in once and reusing the session makes the suite much faster and removes repeated UI steps that add flakiness.

🤔 How many tests should the project have?

Quality matters more than quantity. Around 20 to 30 well-designed, independent tests covering the scenarios above is a solid result.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright Test Agents: Planner, Generator and Healer Explained

Playwright now ships with AI agents that plan, generate and heal tests. In this lesson you will set them up, write a seed test, turn a Markdown test plan into Playwright tests, and use the healer safely when the UI changes.

📖 What You’ll Learn: what the planner, generator and healer agents do, init-agents for VS Code, Claude, Codex and OpenCode, the seed test, reviewing Markdown test plans, generating tests, healing failures, your role at each step, and best practices.


🤝 What Are Playwright Test Agents?

Playwright Test Agents are three ready-made AI agents, shipped with Playwright, that help you plan, write and maintain end-to-end tests:

AgentInputOutput
🎭 PlannerYour app (plus a seed test and optional requirements)A Markdown test plan in specs/
🎭 GeneratorThe Markdown planPlaywright Test files in tests/, with locators and assertions verified live in the browser
🎭 HealerA failing testA fixed test (locators, waits, data), or a skipped test if it believes the feature is really broken

They run inside AI coding tools (VS Code with Copilot, Claude Code, Codex, OpenCode) and use Playwright’s browser tools behind the scenes, similar to Playwright MCP. You can use them one at a time, in sequence, or as a loop.


⚙️ Set Up the Agents

Start from a working Playwright TypeScript project (installation) on a recent Playwright version, then generate the agent definitions for your AI tool:

npx playwright init-agents --loop=vscode     # VS Code (GitHub Copilot agent mode)
npx playwright init-agents --loop=claude     # Claude Code
npx playwright init-agents --loop=codex      # Codex
npx playwright init-agents --loop=opencode   # OpenCode

📝 Note: For VS Code, the agentic experience needs VS Code 1.105 or newer. Re-run init-agents whenever you update Playwright, so the agent definitions match the new version.

After initialization your project looks like this:

.github/                     # agent definitions (location depends on the AI tool)
specs/                       # human-readable Markdown test plans
tests/
  └── seed.spec.ts           # seed test: sets up the environment for the agents
playwright.config.ts

🌱 The Seed Test

The seed test prepares everything the agents need to start: navigation to the app, login, fixtures and global setup. The planner runs it first, and generated tests copy its setup. Keep it small:

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

test('seed', 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');
});

If your project uses custom fixtures or a logged-in storage state, use them in the seed test so generated tests follow the same pattern.


🗺️ Step 1: The Planner Writes a Test Plan

Open your AI tool’s chat, choose the planner agent and describe what to cover:

💬 “Using the seed test, create a test plan for the cart and checkout flows of Sauce Demo: adding and removing items, cart badge, checkout information validation and order completion.”

The planner explores the app in a real browser and saves a plan such as specs/cart-and-checkout.md:

# Cart and Checkout Test Plan

## Application Overview
Sauce Demo lets a logged-in user add products to a cart, review the cart,
enter checkout information and complete an order.

## Test Scenarios

### 1. Cart
**Seed:** tests/seed.spec.ts

#### 1.1 Add a single product
**Steps:**
1. Click "Add to cart" for Sauce Labs Backpack
**Expected Results:**
- The cart badge shows 1
- The button changes to "Remove"

#### 1.2 Remove a product from the cart page
...

### 2. Checkout
#### 2.1 Postal code is required
...

💡 Tip: Review and edit the plan before generating tests. This is where your testing knowledge matters most: add negative cases, remove duplicates, and make the expected results precise. A Product Requirements Document (PRD) given to the planner improves the plan.


🛠️ Step 2: The Generator Writes the Tests

Choose the generator agent and point it at the plan:

💬 “Generate tests for section 1 of specs/cart-and-checkout.md.”

The generator walks through each scenario in the browser, checks that locators and assertions really work, and writes files into tests/, for example:

// tests/cart/add-single-product.spec.ts
// spec: specs/cart-and-checkout.md
// seed: tests/seed.spec.ts
import { test, expect } from '@playwright/test';

test.describe('Cart', () => {
  test('Add a single product', 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.locator('[data-test="add-to-cart-sauce-labs-backpack"]').click();
    await expect(page.locator('.shopping_cart_badge')).toHaveText('1');
    await expect(page.locator('[data-test="remove-sauce-labs-backpack"]')).toBeVisible();
  });
});

Generated code differs between runs and versions; always read it, run it, and refactor it into your framework structure (page objects, fixtures, data files).


🩹 Step 3: The Healer Fixes Failing Tests

When the UI changes and tests fail, choose the healer agent:

💬 “Run the cart tests and fix any failures.”

The healer:

  1. Runs the failing test.
  2. Inspects the current UI to find equivalent elements or flows.
  3. Patches the test: an updated locator, a missing wait condition, adjusted test data.
  4. Re-runs it until it passes, or marks the test as skipped if it concludes that the application itself is broken.

⚠️ Common mistake: A healer that “fixes” a test can also hide a real bug, for example by changing an expected value to match a wrong result. Review every healed diff in a pull request, exactly as you would review a colleague’s change.


🔁 Putting It Together

StepAgentYour role
1. PlanPlannerProvide seed test and requirements, review the plan
2. GenerateGeneratorReview code, refactor into page objects, add to CI
3. MaintainHealerReview healed changes; investigate skipped tests as possible bugs

Run the resulting tests like any other suite: locally, in GitHub Actions or Jenkins. The agents speed up writing and maintenance; the suite itself stays plain, deterministic Playwright code.


✅ Best Practices

  • Start small: one feature, one plan, a handful of tests.
  • Keep the seed test fast and reliable; every generated test depends on it.
  • Use test environments and test accounts only.
  • Store plans (specs/) in Git next to the tests; they document coverage for the team.
  • Require code review for generated and healed tests.
  • Combine with tags so agent-generated tests are easy to find and run.

📝 Assignment

  1. In your Sauce Demo project, run npx playwright init-agents for the AI tool you use.
  2. Write a seed test that logs in and asserts the products page.
  3. Ask the planner for a test plan covering sorting and the cart. Review it and add two negative scenarios yourself.
  4. Ask the generator to create tests for the sorting section. Run them and fix anything that fails.
  5. Change one locator in a generated test to something wrong, then ask the healer to fix it. Review its diff.
  6. Bonus: refactor the generated tests to use your page objects and fixtures from Project 2.

❓ FAQ

🤔 What are Playwright Test Agents?

Three AI agents included with Playwright: a planner that writes Markdown test plans, a generator that turns plans into Playwright tests, and a healer that repairs failing tests.

🤔 How do I set up Playwright Test Agents?

Run npx playwright init-agents --loop=vscode (or claude, codex, opencode) in your Playwright project, add a seed test, then use the agents from your AI tool’s chat.

🤔 What is the seed test in Playwright agents?

A test that sets up the environment (navigation, login, fixtures). The planner runs it first and generated tests reuse its setup.

🤔 Can the healer agent hide real bugs?

It can if you accept changes blindly. The healer skips tests it believes reflect broken functionality, but you should review every healed change.

🤔 What is the difference between Playwright Test Agents and Playwright MCP?

Playwright MCP is a general browser tool for any AI client. Test Agents are purpose-built agents for planning, generating and healing Playwright Test suites.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright MCP: Browser Automation with AI Agents (Setup and Examples)

Playwright MCP gives AI assistants a real browser they can drive with Playwright. In this lesson you will understand how it works, install it in popular AI clients, learn its tools and options, and use it for exploration, test drafting and debugging.

📖 What You’ll Learn: what MCP and Playwright MCP are, accessibility snapshots vs screenshots, installation in Claude Code, VS Code and Cursor, the browser tools, configuration options, practical tester workflows, safety practices, and MCP vs Test Agents.


🤖 What Is Playwright MCP?

MCP (Model Context Protocol) is an open standard that lets AI assistants use external tools. Playwright MCP (@playwright/mcp) is Microsoft’s MCP server that gives an AI assistant, such as Claude, GitHub Copilot in VS Code or Cursor, a real browser it can control through Playwright.

With it, you can ask an assistant in plain English:

  • “Open the Sauce Demo site, log in as standard_user and tell me what is on the products page.”
  • “Check whether the checkout form shows an error when the postcode is empty.”
  • “Explore this page and write a Playwright TypeScript test for adding two items to the cart.”

The assistant then navigates, clicks, types and reads the page step by step, using Playwright under the hood.

New to AI agents? Read Fundamentals of Agentic AI for Beginners first.


🧠 How It Works: Accessibility Snapshots, Not Screenshots

By default, Playwright MCP does not send screenshots to the AI. It sends an accessibility snapshot: a structured, text-based view of the page with roles, names and references for each element, the same information behind getByRole locators.

ApproachPlaywright MCP defaultScreenshot-based agents
Input to the AIStructured accessibility tree (text)Pixels
Speed and costFast, smallSlower, larger
PrecisionActs on exact elementsGuesses coordinates
Needs a vision modelNoYes

Screenshots are still available as a separate tool when the assistant needs to “see” the page.


⚙️ Install Playwright MCP

You need Node.js (see Install Playwright) and an MCP-capable AI client.

Standard configuration (most clients)

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp@latest"]
    }
  }
}

Claude Code

claude mcp add playwright npx @playwright/mcp@latest

VS Code (GitHub Copilot agent mode)

code --add-mcp '{"name":"playwright","command":"npx","args":["@playwright/mcp@latest"]}'

Cursor

Open Cursor Settings, MCP, Add new MCP Server, choose the command type and enter npx @playwright/mcp@latest.

After installing, restart the client and check that the Playwright tools are listed and enabled.


🧰 The Tools the AI Gets

The server exposes browser actions as tools. The most important ones:

ToolWhat the AI can do
browser_navigate, browser_navigate_backOpen URLs, go back
browser_snapshotRead the page as an accessibility snapshot
browser_click, browser_hover, browser_dragMouse interactions
browser_type, browser_fill_form, browser_press_keyTyping and keyboard
browser_select_option, browser_file_uploadDropdowns and uploads
browser_handle_dialogAccept or dismiss alerts
browser_wait_forWait for text to appear or disappear
browser_tabsList, open, switch and close tabs
browser_take_screenshotCapture an image when visual context is needed
browser_console_messages, browser_network_requestsRead console logs and network traffic
browser_evaluateRun JavaScript on the page
browser_close, browser_resizeManage the browser window

🎛️ Useful Options

Add options to the args array in the configuration:

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp@latest", "--browser", "chrome", "--isolated", "--device", "iPhone 15"]
    }
  }
}
OptionPurpose
--headlessRun without a visible window (headed is the default)
--browserchrome, firefox, webkit or msedge
--isolatedKeep the browser profile in memory; nothing is saved between sessions
--user-data-dirUse a persistent profile folder
--storage-stateStart an isolated session with saved cookies and storage (login sessions)
--deviceEmulate a device such as "iPhone 15" (mobile emulation)
--capsEnable extra capabilities: vision, pdf, devtools
--output-dirFolder for screenshots and other output files

🧪 Practical Workflows for Testers

1. Exploratory testing assistant

💬 “Using the Playwright tools, open https://www.saucedemo.com, log in as standard_user with password secret_sauce, sort products by price high to low, and report the first three products and their prices.”

The assistant performs the steps and reports what it saw, which is useful for quick checks and reproducing bugs.

2. Generate a first draft of a test

💬 “Explore the checkout flow on Sauce Demo with the browser, then write a Playwright Test in TypeScript that adds the backpack, checks out with test data, and asserts the order confirmation. Use getByRole and data-test locators.”

Because the assistant has seen the real page, its locators are usually accurate. Treat the result like Codegen output: review it, add assertions and move it into your framework structure.

3. Debug a failing test

💬 “This test fails at the checkout button. Open the page, take a snapshot at that step, and explain why the button cannot be clicked.”

The assistant can read console errors and network requests to suggest causes.


⚠️ Safety and Good Practice

  • Use test environments and test accounts. The AI acts with whatever access the browser has.
  • Prefer --isolated so sessions do not reuse real cookies or logins.
  • Review every action your client asks to approve, especially form submissions.
  • Do not share secrets in prompts; use --storage-state with a test session instead.
  • Keep humans in charge of assertions. The AI can draft tests, but you decide what “correct” means.

🔄 Playwright MCP vs Playwright Test Agents

Playwright MCPPlaywright Test Agents
What it isAn MCP server giving any AI client browser controlReady-made planner, generator and healer agents for Playwright Test
Best forExploration, ad-hoc tasks, drafting tests, debuggingA structured loop: plan, generate and heal a test suite
OutputWhatever you ask forMarkdown test plans and Playwright test files

📝 Assignment

  1. Install Playwright MCP in your AI client (Claude Code, VS Code or Cursor) and confirm the tools are listed.
  2. Ask the assistant to open https://www.saucedemo.com and describe the login page using a snapshot.
  3. Ask it to log in, add two products to the cart and report the cart badge number.
  4. Ask it to write a Playwright TypeScript test for that flow, then run the test locally and fix anything that fails.
  5. Restart the server with --isolated --device "iPhone 15" and repeat task 2. What changed?
  6. Bonus: compare the AI-generated test with your own test from your first Playwright test. Which locators and assertions are better?

❓ FAQ

🤔 What is Playwright MCP?

An MCP server from Microsoft (@playwright/mcp) that lets AI assistants control a real browser through Playwright, using accessibility snapshots to understand the page.

🤔 How do I install Playwright MCP in Claude Code?

Run claude mcp add playwright npx @playwright/mcp@latest, then restart Claude Code.

🤔 Does Playwright MCP use screenshots?

Not by default. It uses accessibility snapshots, which are faster and more precise. A screenshot tool is available when visual context is needed.

🤔 Can Playwright MCP replace my test suite?

No. It is excellent for exploration, drafting and debugging, but a reliable regression suite still needs reviewed, deterministic Playwright tests running in CI.

🤔 Which browsers does Playwright MCP support?

Chrome, Firefox, WebKit and Microsoft Edge, selected with the --browser option.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Run Playwright Tests in Jenkins: Jenkinsfile, Docker, Reports and Credentials

Many companies run their pipelines on Jenkins. In this lesson you will run a Playwright TypeScript suite in a Jenkins pipeline using the official Docker image, publish JUnit results and the HTML report, handle credentials, add parameters and schedules, and shard large suites.

📖 What You’ll Learn: preparing the config for Jenkins, a Jenkinsfile with the official Docker image, agents without Docker and Windows agents, credentials, parameters and cron triggers, parallel shards, viewing the HTML report despite Jenkins CSP, and a Jenkins checklist.


🏗️ Why Jenkins?

Jenkins is the most widely used self-hosted CI server, especially in enterprises and service companies. If your team already builds and deploys with Jenkins, running Playwright there keeps everything in one pipeline. Playwright works well in Jenkins with a few Jenkins-specific settings you will learn here.

You need:

  • A Jenkins server (or a local one) with the Pipeline, Git, JUnit and HTML Publisher plugins.
  • Either Docker on the Jenkins agent (recommended) or Node.js installed on the agent.
  • Your Playwright project in a Git repository.

⚙️ Step 1: Prepare the Playwright Config for Jenkins

Jenkins does not set the CI environment variable that the default config checks, so you will set it in the pipeline. Also add a JUnit reporter so Jenkins can show test results natively (reporters):

// playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 2 : undefined,
  reporter: [
    ['line'],
    ['html', { open: 'never' }],
    ['junit', { outputFile: 'results/junit.xml' }],
  ],
  use: {
    baseURL: process.env.BASE_URL ?? 'https://www.saucedemo.com',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
  },
});

🐳 Step 2: Jenkinsfile with the Official Docker Image (Recommended)

Create a Jenkinsfile in the project root. The official Playwright image already contains Node.js, browsers and all system libraries:

pipeline {
  agent {
    docker {
      // Use the SAME version as @playwright/test in your package.json
      image 'mcr.microsoft.com/playwright:v1.xx.x-noble'
      args '--ipc=host'
    }
  }

  environment {
    CI = 'true'
    BASE_URL = 'https://www.saucedemo.com'
  }

  options {
    timeout(time: 60, unit: 'MINUTES')
  }

  stages {
    stage('Install') {
      steps {
        sh 'npm ci'
      }
    }
    stage('Test') {
      steps {
        sh 'npx playwright test'
      }
    }
  }

  post {
    always {
      junit allowEmptyResults: true, testResults: 'results/junit.xml'
      archiveArtifacts artifacts: 'playwright-report/**, test-results/**', allowEmptyArchive: true
      publishHTML(target: [
        allowMissing: true,
        alwaysLinkToLastBuild: true,
        keepAll: true,
        reportDir: 'playwright-report',
        reportFiles: 'index.html',
        reportName: 'Playwright Report'
      ])
    }
  }
}

What each part does:

SectionPurpose
agent { docker { ... } }Runs the build inside the official Playwright container
args '--ipc=host'Recommended for Chromium in Docker to avoid running out of shared memory
environmentSets CI so the config uses CI settings, plus non-secret variables
npm ciInstalls exact dependency versions from package-lock.json
junitShows passed and failed tests and trends in Jenkins
archiveArtifactsKeeps the HTML report, traces and screenshots for download
publishHTMLAdds a Playwright Report link to the build page

⚠️ Common mistake: The image tag must match your @playwright/test version exactly. A mismatch causes “Executable doesn’t exist” errors because the browsers in the image are a different build. See Playwright with Docker and Kubernetes.


🖥️ Option: Agent Without Docker

If your agent cannot run Docker, install Node.js (for example with the NodeJS plugin) and the browsers in the pipeline:

pipeline {
  agent { label 'linux' }
  tools { nodejs 'node-lts' }          // name configured in Manage Jenkins, Tools
  environment { CI = 'true' }
  stages {
    stage('Install') {
      steps {
        sh 'npm ci'
        sh 'npx playwright install --with-deps'   // needs root or sudo on Linux for system libraries
      }
    }
    stage('Test') {
      steps { sh 'npx playwright test' }
    }
  }
}

On a Windows agent use bat instead of sh, for example bat 'npx playwright test', and npx playwright install without --with-deps.


🔐 Step 3: Credentials

Store passwords and tokens in Manage Jenkins, Credentials, then expose them only to the test step:

stage('Test') {
  steps {
    withCredentials([usernamePassword(credentialsId: 'qa-test-user',
                                      usernameVariable: 'TEST_USER',
                                      passwordVariable: 'TEST_PASSWORD')]) {
      sh 'npx playwright test'
    }
  }
}

Your tests read process.env.TEST_USER and process.env.TEST_PASSWORD (environment variables). Jenkins masks them in the console log.


🎛️ Step 4: Parameters, Tags and Schedules

Let people choose what to run, and schedule nightly regression:

pipeline {
  agent { docker { image 'mcr.microsoft.com/playwright:v1.xx.x-noble'; args '--ipc=host' } }
  parameters {
    choice(name: 'SUITE', choices: ['@smoke', '@regression', 'all'], description: 'Which tests to run')
    choice(name: 'BROWSER', choices: ['chromium', 'firefox', 'webkit'], description: 'Browser project')
  }
  triggers { cron('H 2 * * *') }       // nightly, around 02:00 server time
  environment { CI = 'true' }
  stages {
    stage('Install') { steps { sh 'npm ci' } }
    stage('Test') {
      steps {
        script {
          def grep = params.SUITE == 'all' ? '' : "--grep '" + params.SUITE + "'"
          sh "npx playwright test --project=" + params.BROWSER + " " + grep
        }
      }
    }
  }
}

Tags are explained in group, tag and filter tests.


⚡ Step 5: Parallel Shards in Jenkins

Split a large suite into parallel stages with --shard (parallel execution):

stage('Test') {
  parallel {
    stage('Shard 1') { steps { sh 'npx playwright test --shard=1/3 --reporter=blob' } }
    stage('Shard 2') { steps { sh 'npx playwright test --shard=2/3 --reporter=blob' } }
    stage('Shard 3') { steps { sh 'npx playwright test --shard=3/3 --reporter=blob' } }
  }
}

When shards run on different agents, stash each blob-report folder under a different name, unstash them into one folder, and run npx playwright merge-reports --reporter html <folder> in a final stage.


🧾 Viewing the HTML Report in Jenkins

Jenkins serves published HTML with a strict Content Security Policy that blocks JavaScript. Because the Playwright HTML report is a JavaScript application, the Playwright Report link may show a blank page. Options:

  1. Download the archived playwright-report artifact and open it locally with npx playwright show-report <folder> (safest).
  2. Ask your Jenkins administrator to relax the CSP for HTML reports. This affects security for all published reports, so it is an admin decision.
  3. Rely on the JUnit test results in Jenkins for pass/fail and trends, and download traces only for failures (Trace Viewer).

✅ Jenkins Checklist

  • Jenkinsfile committed to the repository (pipeline as code).
  • Official Docker image with a tag matching @playwright/test, and --ipc=host.
  • CI = 'true' set in environment.
  • JUnit reporter for native results; HTML report and traces archived.
  • Secrets only through Jenkins Credentials.
  • Parameters for suite and browser; nightly cron trigger for regression.

📝 Assignment

  1. Add junit and html reporters to your config and a Jenkinsfile using the official Docker image.
  2. Create a Pipeline job in Jenkins pointing to your repository and run it.
  3. Break a test on purpose and find it in the Jenkins Test Result view and in the archived report.
  4. Move a password into Jenkins Credentials and use withCredentials.
  5. Add SUITE and BROWSER parameters and run only @smoke in Firefox.
  6. Add a nightly cron trigger.
  7. Bonus: split the suite into three parallel shard stages.

❓ FAQ

🤔 How do I run Playwright tests in Jenkins?

Create a Jenkinsfile that runs npm ci and npx playwright test, preferably inside the official mcr.microsoft.com/playwright Docker image, and publish JUnit results and the HTML report in the post section.

🤔 Why does the Playwright HTML report show a blank page in Jenkins?

Jenkins’ Content Security Policy blocks the report’s JavaScript. Download the archived report and open it locally, or have an administrator adjust the CSP.

🤔 Why does my Playwright config ignore CI settings in Jenkins?

Jenkins does not set CI=true by default. Add CI = 'true' to the pipeline’s environment block.

🤔 Do I need Docker to run Playwright in Jenkins?

No, but it is recommended. Without Docker, install Node.js on the agent and run npx playwright install --with-deps, which needs system packages on Linux.

🤔 How do I pass secrets to Playwright tests in Jenkins?

Store them in Jenkins Credentials and wrap the test step in withCredentials; read them in tests through process.env.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Run Playwright Tests in GitHub Actions: CI Workflow, Secrets, Sharding and Reports

Automation pays off when it runs on every change. In this lesson you will run your Playwright TypeScript suite in GitHub Actions, handle secrets, read reports and traces from CI, shard across parallel jobs, and schedule nightly regression runs.

📖 What You’ll Learn: the Playwright workflow YAML step by step, CI-friendly config, secrets and variables, downloading reports and traces, sharding with a matrix and merged report, running in the official Docker image, nightly and manual runs, and a CI checklist.


🚀 Why Run Playwright in CI?

Tests that only run on your laptop protect nobody. Continuous Integration (CI) runs your suite automatically on every push and pull request, so broken code is caught before it is merged. GitHub Actions is the most common choice for projects on GitHub, and Playwright supports it out of the box.

New to GitHub Actions itself? Start with the GitHub Actions complete roadmap and GitHub Actions fundamentals for beginners.


🧾 Step 1: The Basic Workflow

If you answered Yes to “Add a GitHub Actions workflow?” during installation, you already have this file. Otherwise create .github/workflows/playwright.yml:

name: Playwright Tests
on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    timeout-minutes: 60
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: lts/*

      - name: Install dependencies
        run: npm ci

      - name: Install Playwright browsers
        run: npx playwright install --with-deps

      - name: Run Playwright tests
        run: npx playwright test

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

What each step does:

StepPurpose
actions/checkoutDownloads your repository
actions/setup-nodeInstalls Node.js
npm ciInstalls the exact versions from package-lock.json
npx playwright install --with-depsDownloads browsers and Linux system libraries
npx playwright testRuns the suite
upload-artifactSaves the HTML report (with traces and screenshots) even when tests fail

⚠️ Common mistake: Always commit package-lock.json. npm ci fails without it, and it guarantees CI uses the same Playwright version as your machine.


⚙️ Step 2: CI-Friendly Config

The default config already reacts to process.env.CI, which GitHub sets automatically:

export default defineConfig({
  forbidOnly: !!process.env.CI,          // fail if test.only was committed
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 2 : undefined,
  reporter: process.env.CI
    ? [['dot'], ['github'], ['html', { open: 'never' }]]
    : [['list'], ['html', { open: 'on-failure' }]],
  use: {
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
  },
});

The github reporter adds annotations to the pull request, pointing at the exact failing lines.


🔐 Step 3: Secrets and Environment Variables

Never commit passwords or tokens. Add them under Settings, Secrets and variables, Actions in your repository, then pass them to the job:

      - name: Run Playwright tests
        run: npx playwright test
        env:
          BASE_URL: ${{ vars.BASE_URL }}
          TEST_USER: ${{ secrets.TEST_USER }}
          TEST_PASSWORD: ${{ secrets.TEST_PASSWORD }}

Read them in your config and tests with process.env.BASE_URL (environment variables). GitHub masks secret values in logs.


📥 Step 4: Read the Results

  1. Open the Actions tab and the workflow run.
  2. Failing tests appear as annotations in the summary and on the pull request.
  3. Download the playwright-report artifact, unzip it and run npx playwright show-report playwright-report.
  4. Open a failed test and its trace (Trace Viewer).

🧩 Step 5: Shard Across Parallel Jobs

For large suites, split tests across several machines with a matrix and merge the reports (parallel execution and sharding):

name: Playwright Tests (sharded)
on: [push, pull_request]

jobs:
  playwright-tests:
    timeout-minutes: 60
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        shardIndex: [1, 2, 3, 4]
        shardTotal: [4]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: lts/*
      - run: npm ci
      - run: npx playwright install --with-deps
      - name: Run shard
        run: npx playwright test --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }} --reporter=blob
      - uses: actions/upload-artifact@v4
        if: ${{ !cancelled() }}
        with:
          name: blob-report-${{ matrix.shardIndex }}
          path: blob-report
          retention-days: 1

  merge-reports:
    if: ${{ !cancelled() }}
    needs: [playwright-tests]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: lts/*
      - run: npm ci
      - uses: actions/download-artifact@v4
        with:
          path: all-blob-reports
          pattern: blob-report-*
          merge-multiple: true
      - name: Merge into one HTML report
        run: npx playwright merge-reports --reporter html ./all-blob-reports
      - uses: actions/upload-artifact@v4
        with:
          name: html-report--attempt-${{ github.run_attempt }}
          path: playwright-report
          retention-days: 14

🐳 Option: Run Inside the Official Playwright Docker Image

The official image already contains browsers and system libraries, which also gives consistent screenshots for visual tests:

jobs:
  test:
    runs-on: ubuntu-latest
    container:
      image: mcr.microsoft.com/playwright:v1.xx.x-noble   # use the SAME version as @playwright/test in package.json
      options: --user 1001
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: lts/*
      - run: npm ci
      - run: npx playwright test

📝 Note: The image tag must match your installed @playwright/test version, otherwise Playwright looks for browser builds that are not in the image. More in Playwright with Docker and Kubernetes.


⏰ Nightly and Manual Runs

Run the full cross-browser regression every night and allow manual runs from the Actions tab:

on:
  schedule:
    - cron: '30 20 * * *'      # 20:30 UTC = 02:00 IST
  workflow_dispatch:
    inputs:
      grep:
        description: 'Tag to run, e.g. @smoke'
        required: false
        default: ''

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      # ...checkout, setup-node, npm ci, install browsers...
      - run: npx playwright test --grep "${{ github.event.inputs.grep }}"

Combine with tags: @smoke on every pull request, the full suite nightly.


✅ CI Checklist

  • package-lock.json committed, npm ci in CI.
  • Browsers installed with --with-deps (or the official Docker image).
  • forbidOnly, retries and trace: 'on-first-retry' enabled for CI.
  • HTML report uploaded with if: !cancelled() so you get it when tests fail.
  • Secrets in GitHub Secrets, never in code.
  • Pull-request gate fast (smoke or Chromium only); full matrix nightly.

📝 Assignment

  1. Push your Sauce Demo project to a GitHub repository with the basic workflow and watch it run in the Actions tab.
  2. Break a test on purpose, push, and find the failure annotation and the trace in the downloaded report.
  3. Move the base URL into a repository variable and a password into a secret, and read them in the config.
  4. Add the github and dot reporters for CI only.
  5. Convert the workflow to 2 shards with a merged HTML report.
  6. Add a nightly schedule and a manual workflow_dispatch with a grep input.
  7. Bonus: run the job inside the official Playwright Docker image matching your version.

❓ FAQ

🤔 How do I run Playwright tests in GitHub Actions?

Add a workflow that checks out the code, sets up Node.js, runs npm ci, npx playwright install --with-deps and npx playwright test, then uploads playwright-report as an artifact.

🤔 How do I see the Playwright report from GitHub Actions?

Download the playwright-report artifact from the workflow run, unzip it and run npx playwright show-report <folder>, or publish it to GitHub Pages.

🤔 How do I use secrets in Playwright GitHub Actions?

Store them in the repository’s Actions secrets and pass them as env values with ${{ secrets.NAME }}; read them with process.env.NAME.

🤔 How do I run Playwright tests in parallel on GitHub Actions?

Use a matrix with --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }} and the blob reporter, then merge the blob reports in a final job.

🤔 Should I cache Playwright browsers in GitHub Actions?

Usually not. Restoring a large cache takes about as long as downloading browsers, and the system dependencies still need installing. The official Docker image is a faster alternative.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in