Write and Run Your First Playwright Test with TypeScript

Now that Playwright is installed, it is time to write real tests. In this lesson you will understand every line of a Playwright test, automate a login page, run it in different ways, read a failure message, and view the HTML report.

📖 What You’ll Learn: test anatomy (test, expect, page fixture, async/await), writing a login test, running it from the CLI and VS Code, reading failure messages, negative tests with describe and beforeEach, the HTML report and baseURL.


🧱 Anatomy of a Playwright Test

Open tests/example.spec.ts from your project. Every Playwright test has the same building blocks:

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

test('has title', async ({ page }) => {               // 2. test name + async function
  await page.goto('https://playwright.dev/');         // 3. actions use await
  await expect(page).toHaveTitle(/Playwright/);       // 4. assertion
});
  1. Import test (to declare tests) and expect (to make assertions) from @playwright/test.
  2. test(name, function): the name appears in reports, so make it describe the behaviour. The function is async because browser actions take time.
  3. { page } is a fixture: Playwright creates a fresh browser tab for each test and passes it in. You never launch the browser yourself.
  4. await in front of every action and assertion, so each step finishes before the next starts.
  5. expect(…) checks the result. Web-first assertions like toHaveTitle retry automatically until they pass or time out.

✍️ Write Your First Real Test: Login

We will automate the login page of Sauce Demo (https://www.saucedemo.com), a free practice shop. Create a new file tests/login.spec.ts:

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

test('standard user can log in', async ({ page }) => {
  // Arrange: open the login page
  await page.goto('https://www.saucedemo.com/');

  // Act: fill the form and submit
  await page.getByPlaceholder('Username').fill('standard_user');
  await page.getByPlaceholder('Password').fill('secret_sauce');
  await page.getByRole('button', { name: 'Login' }).click();

  // Assert: we are on the products page
  await expect(page).toHaveURL(/inventory\.html/);
  await expect(page.locator('.title')).toHaveText('Products');
});

What each line does:

  • page.goto(url) opens the page and waits for it to load.
  • page.getByPlaceholder('Username') finds the input by its placeholder text. This is a locator; you will master locators in Playwright Locators.
  • fill() clears the input and types the text.
  • getByRole('button', { name: 'Login' }) finds the button the way a user or screen reader sees it.
  • toHaveURL and toHaveText verify the outcome.

💡 Tip: Structure tests as Arrange, Act, Assert: set up, perform the user action, then verify. It keeps tests easy to read.


▶️ Run the Test

Run only this file, in Chromium, with the browser visible:

npx playwright test login.spec.ts --project=chromium --headed

Or run it from VS Code: open the Testing view, tick Show browser, and click ▶ next to the test name. When it passes you see a green tick; in the terminal you see:

Running 1 test using 1 worker
  ✓  1 [chromium] › tests/login.spec.ts:3:5 › standard user can log in (1.9s)
  1 passed (2.6s)

❌ Make It Fail on Purpose (and Read the Error)

Learning to read failures is as important as writing tests. Change the expected text to 'Product' (without the s) and run again. Playwright prints exactly what went wrong:

Error: Timed out 5000ms waiting for expect(locator).toHaveText(expected)

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

The message shows the locator, what was expected and what was received. Change it back to 'Products' so the test passes again.


🧪 Add a Negative Test and Group Tests

Good test suites cover failures too. Use test.describe to group related tests, and test.beforeEach to share setup:

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

test.describe('Login page', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('https://www.saucedemo.com/');
  });

  test('standard user can log in', async ({ page }) => {
    await page.getByPlaceholder('Username').fill('standard_user');
    await page.getByPlaceholder('Password').fill('secret_sauce');
    await page.getByRole('button', { name: 'Login' }).click();
    await expect(page).toHaveURL(/inventory\.html/);
  });

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

  test('empty form shows username required', async ({ page }) => {
    await page.getByRole('button', { name: 'Login' }).click();
    await expect(page.locator('[data-test="error"]')).toContainText('Username is required');
  });
});

Hooks such as beforeEach get a full lesson later in the course.


📊 View the HTML Report

npx playwright test
npx playwright show-report

The report lists each test per browser, with its steps, duration and, for failures, the error, screenshot and trace (depending on your config). Click a test to see every action that ran.


🌐 Use baseURL to Shorten Your Tests

Instead of repeating the full URL, set baseURL in playwright.config.ts:

// playwright.config.ts (inside defineConfig)
use: {
  baseURL: 'https://www.saucedemo.com',
},

Now await page.goto('/') opens the home page. Learn every config option in playwright.config.ts explained.


✅ Beginner Mistakes to Avoid

  • Forgetting await: the test may finish before the action happens. Always write await before page.* actions and expect for locators.
  • Using sleeps: do not add fixed waits; Playwright auto-waits. See Playwright waits.
  • Vague test names: 'test1' tells you nothing in a report. Describe the behaviour.
  • Tests that depend on each other: each test should work alone, in any order.

📝 Assignment

Use https://www.saucedemo.com for all tasks and put them in tests/login.spec.ts:

  1. Write a test that logs in as problem_user and verifies the products page title.
  2. Write a test that enters a wrong password and checks the error contains Username and password do not match.
  3. Write a test that logs in, adds Sauce Labs Backpack to the cart, and verifies the cart badge shows 1 (page.locator('.shopping_cart_badge')).
  4. Run all tests in Chromium with --headed, then in all browsers, and compare the HTML report.
  5. Bonus: make one test fail on purpose and write down the three pieces of information the error message gave you.

❓ FAQ

🤔 How do I write my first Playwright test?

Create a .spec.ts file in the tests folder, import test and expect from @playwright/test, write test('name', async ({ page }) => { ... }) with actions and assertions, and run npx playwright test.

🤔 Why does every Playwright test use async and await?

Browser actions take time and return Promises. await makes each step finish before the next one runs. Learn more in TypeScript Functions and TypeScript for Playwright.

🤔 How do I run a single Playwright test?

Run npx playwright test login.spec.ts for one file, add -g "test name" to filter by title, or click ▶ in the VS Code Testing view. All options are in Playwright CLI commands.

🤔 Why does my test run three times?

The default config has three projects (Chromium, Firefox, WebKit), so each test runs once per browser. Use --project=chromium to run one browser.

🤔 How do I see the browser while the test runs?

Add --headed to the command, use --ui for UI mode, or tick Show browser in the VS Code extension.

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

How to Install Playwright with TypeScript and Set Up VS Code (Step by Step)

In this lesson you will set up everything you need to write Playwright tests: Node.js, Visual Studio Code, a new Playwright TypeScript project and the official VS Code extension. It takes about 15 minutes, and at the end you will run your first tests in three browsers.

📖 What You’ll Learn: installing Node.js and VS Code, creating a project with npm init playwright, the generated files, running sample tests, the HTML report, the Playwright VS Code extension, updating Playwright and fixing common installation errors.


✅ Prerequisites

You need only three things:

ToolWhyWhere to get it
Node.js (current LTS)Runs Playwright and installs packages with npmnodejs.org
Visual Studio CodeEditor with the official Playwright extensioncode.visualstudio.com
A terminalTo run commandsBuilt into VS Code (View, Terminal)

Git is optional now but useful later when you push your project to GitHub and run it in CI.


1️⃣ Step 1: Install Node.js

  1. Go to nodejs.org and download the LTS version for your operating system.
  2. Run the installer and keep the default options (npm is installed together with Node.js).
  3. Open a new terminal and check the versions:
node -v
npm -v

Both commands should print a version number, for example v22.x.x and 10.x.x.

⚠️ Common mistake: If you see “node is not recognized” on Windows, close and reopen the terminal (or VS Code) so it picks up the new PATH. If it still fails, reinstall Node.js and keep “Add to PATH” selected.


2️⃣ Step 2: Install Visual Studio Code

Download VS Code from code.visualstudio.com and install it. Then create an empty folder for your project, for example playwright-course, and open it with File, Open Folder.


3️⃣ Step 3: Create a Playwright Project

Open the VS Code terminal (Ctrl + ` or View, Terminal) inside your empty folder and run:

npm init playwright@latest

The installer asks a few questions. Choose these answers for this course:

QuestionAnswer
Do you want to use TypeScript or JavaScript?TypeScript
Where to put your end-to-end tests?tests (default)
Add a GitHub Actions workflow?Yes (useful later; you can also say No)
Install Playwright browsers?Yes

Playwright then installs the @playwright/test package and downloads Chromium, Firefox and WebKit. This can take a few minutes the first time.

📝 Note: On Linux, add the system dependencies with npx playwright install --with-deps. On Windows and macOS the browsers work without extra steps.


📂 Step 4: Understand the Generated Files

playwright-course/
├── .github/workflows/playwright.yml   # CI workflow (if you chose Yes)
├── node_modules/                      # installed packages (never edit)
├── tests/
│   └── example.spec.ts                # sample test
├── .gitignore                         # ignores reports and results
├── package.json                       # project info and dependencies
├── package-lock.json                  # exact installed versions
└── playwright.config.ts               # Playwright settings
  • tests/: all your test files go here. Files ending in .spec.ts or .test.ts are treated as tests.
  • playwright.config.ts: browsers, timeouts, reporters and more. It has its own lesson: playwright.config.ts explained.
  • package.json: lists @playwright/test as a dev dependency.

▶️ Step 5: Run the Sample Tests

npx playwright test

Playwright runs the sample tests in all three browsers, in parallel and headless (no visible window). You should see output similar to:

Running 6 tests using 4 workers
  6 passed (8.2s)

To open last HTML report run:
  npx playwright show-report

Open the HTML report to see each test, browser and step:

npx playwright show-report

🧩 Step 6: Install the Playwright VS Code Extension

  1. Open the Extensions view in VS Code (Ctrl + Shift + X).
  2. Search for Playwright Test for VSCode published by Microsoft and click Install.
  3. Open the Testing view (the flask icon in the left sidebar). Your tests appear in a tree.

With the extension you can:

  • Run or debug a single test with the green ▶ icon next to it.
  • Tick Show browser to watch tests run.
  • Use Pick locator to click an element in the browser and get a locator.
  • Use Record new to generate a test with Codegen.

💡 Tip: You can also create a new project from the extension: open the Command Palette (Ctrl + Shift + P) and run Test: Install Playwright.


🔄 Updating Playwright Later

Playwright releases a new version roughly every month. To update:

npm install -D @playwright/test@latest
npx playwright install

The second command downloads browser builds that match the new version.


🐞 Common Installation Problems

ProblemFix
npx: command not foundNode.js is not installed or the terminal was not restarted
Browsers fail to download behind a company proxySet the HTTPS_PROXY environment variable, then run npx playwright install
“Executable doesn’t exist” errorBrowsers are missing or outdated: run npx playwright install
Missing libraries on LinuxRun npx playwright install --with-deps
PowerShell blocks npx scriptsRun Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once, or use Command Prompt

📝 Assignment

  1. Install Node.js and VS Code, and paste the output of node -v and npm -v into a notes file.
  2. Create a project with npm init playwright@latest using TypeScript.
  3. Run npx playwright test and open the HTML report. How many tests ran, and in which browsers?
  4. Install the VS Code extension and run only one test from the Testing view with Show browser enabled.
  5. Bonus: run npx playwright --version and note which Playwright version you installed.

❓ FAQ

🤔 How do I install Playwright with TypeScript?

Install Node.js, open an empty folder and run npm init playwright@latest, then choose TypeScript. Playwright creates the project, config file and sample tests, and downloads the browsers.

🤔 Do I need to install TypeScript separately?

No. Playwright runs .ts test files directly. Install the typescript package only if you want to run type checks with npx tsc --noEmit, covered in TypeScript for Playwright.

🤔 Where does Playwright install the browsers?

In a shared cache folder: %USERPROFILE%\AppData\Local\ms-playwright on Windows, ~/Library/Caches/ms-playwright on macOS and ~/.cache/ms-playwright on Linux.

🤔 Can I use Google Chrome instead of the bundled Chromium?

Yes. Set channel: 'chrome' (or 'msedge') in a project in the config file. Run npx playwright install chrome if Chrome is not installed.

🤔 How do I install Playwright in an existing project?

Run npm init playwright@latest in the project folder, or install it manually with npm install -D @playwright/test followed by npx playwright install.

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

What Is Playwright? Features, Architecture and Why Testers Use It

Welcome to Lesson 1 of the free Playwright with TypeScript tutorial. Before writing any code, you will understand what Playwright is, what it can test, how it works under the hood, and why it has become one of the most popular test automation tools.

📖 What You’ll Learn: what Playwright is, what you can automate with it, its key features, the architecture, Browser vs BrowserContext vs Page, Playwright Library vs Playwright Test, supported browsers and languages, and its limitations.


🎭 Playwright in One Sentence

Playwright is a free, open-source framework from Microsoft for automating web browsers and testing web applications end to end. You write code that opens a browser, clicks, types and navigates like a real user, then checks that the application behaves correctly.

It was first released in January 2020 by a Microsoft team that had previously built Puppeteer at Google. Since then it has become one of the fastest-growing test automation tools, and many teams now choose it for new projects instead of Selenium or Cypress.


🧰 What Can You Do with Playwright?

  • End-to-end UI testing: log in, fill forms, add items to a cart, check out, and verify the result.
  • API testing: send GET, POST, PUT and DELETE requests and check responses, in the same framework.
  • Cross-browser testing: run the same test on Chromium (Chrome, Edge), Firefox and WebKit (the engine behind Safari).
  • Mobile web testing: emulate phones and tablets such as iPhone and Pixel (screen size, touch, user agent).
  • Visual testing: compare screenshots to catch unexpected UI changes.
  • Network control: intercept, block or mock requests to test edge cases.
  • Web scraping and automation tasks: generate PDFs, take screenshots and automate repetitive browser work.

⭐ Key Features That Make Playwright Popular

FeatureWhat it means for you
Auto-waitingPlaywright waits for elements to be ready before acting, so you rarely write manual waits
Web-first assertionsexpect(...) checks retry automatically until they pass or time out
Browser contextsEach test gets a fresh, isolated browser profile in milliseconds
Built-in test runnerParallel runs, retries, reports, fixtures and annotations without extra libraries
Multiple languagesJavaScript, TypeScript, Python, Java and .NET
Powerful toolingCodegen (record tests), Inspector, UI mode, Trace Viewer, VS Code extension
Multi-tab and multi-userTest several tabs, windows, users and origins in one test
Free and open sourceApache 2.0 licence, no paid tier required for parallel runs

🏗️ Playwright Architecture Explained Simply

Playwright has three layers:

  1. Your test code (for example a .spec.ts file written in TypeScript).
  2. The Playwright driver, a Node.js process that receives your commands.
  3. The browsers, which the driver controls over a fast, persistent WebSocket connection. For Chromium it uses the Chrome DevTools Protocol; for Firefox and WebKit it uses Playwright’s own patched browser builds that expose similar protocols.

Because the connection stays open, commands do not need a new HTTP request each time, which is one reason Playwright is fast and stable compared with tools based on the classic WebDriver protocol. You can read a full comparison in Playwright vs Selenium vs Cypress.

Browser, Context and Page

These three objects appear in every Playwright test, so learn them now:

  • Browser: a running browser instance such as Chromium.
  • BrowserContext: an isolated session inside the browser, like a fresh incognito window, with its own cookies and storage. Contexts are cheap to create, so every test gets its own.
  • Page: a single tab inside a context. Most of your code uses page.
import { chromium } from 'playwright';

(async () => {
  const browser = await chromium.launch();       // Browser
  const context = await browser.newContext();    // BrowserContext (isolated session)
  const page = await context.newPage();          // Page (a tab)

  await page.goto('https://sqatools.in');
  console.log(await page.title());
  await browser.close();
})();

📝 Note: When you use the Playwright test runner (@playwright/test), it creates the browser, context and page for you and passes page into each test. You will see this in your first test.


📦 Playwright Library vs Playwright Test

Playwright Library (playwright)Playwright Test (@playwright/test)
What it isBrowser automation API onlyFull test framework built on the library
Test runner, assertions, reportsNot includedIncluded
Best forScripts, scraping, custom toolsAutomated testing

In this course we use Playwright Test with TypeScript, the setup recommended by the Playwright team for testing.


🌍 Supported Browsers, Platforms and Languages

  • Browsers: Chromium (also branded Google Chrome and Microsoft Edge), Firefox and WebKit.
  • Operating systems: Windows, macOS and Linux, locally or in CI, headed or headless.
  • Languages: TypeScript, JavaScript, Python, Java and C#/.NET.

⚠️ Limitations to Know

  • Playwright tests web applications. It does not automate native Android or iOS apps (use Appium for those) or desktop apps.
  • WebKit is tested through Playwright’s own build, not the branded Safari application.
  • Some features, such as the full test runner with fixtures, are richest in the TypeScript/JavaScript version.

🗺️ What You Will Learn Next

This lesson is the start of the free Playwright Tutorial with TypeScript. Next you will learn testing fundamentals and compare tools, then install Playwright and write your first test.


📝 Assignment

  1. In your own words, write down the difference between a Browser, a BrowserContext and a Page.
  2. List three features of Playwright that reduce flaky tests, and explain why each helps.
  3. Visit playwright.dev and find the list of supported languages. Which one will you use, and why?
  4. Think of one web application you use daily. Write five user actions you would automate with Playwright.

❓ FAQ

🤔 What is Playwright used for?

Mainly for automated end-to-end testing of web applications across Chromium, Firefox and WebKit. It is also used for API testing, visual testing and general browser automation.

🤔 Is Playwright free?

Yes. Playwright is open source under the Apache 2.0 licence, including parallel execution and all tooling.

🤔 Is Playwright a testing tool or a library?

Both. The playwright package is an automation library, and @playwright/test is a complete testing framework built on top of it.

🤔 Who maintains Playwright?

Microsoft maintains Playwright as an open-source project on GitHub, with frequent releases.

🤔 Is Playwright better than Selenium?

For most new web projects it is faster to set up and less flaky. Selenium still wins for wider language support and some legacy setups. See Playwright vs Selenium vs Cypress.

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright: Handle Alerts, Popups, Dropdowns, iFrames, New Tabs and File Uploads

Alerts, popups, dropdowns, iframes and new tabs are where most beginners get stuck when moving to Playwright. This guide shows the right Playwright API for each situation with runnable TypeScript examples you can try on a free practice site.

📖 What You’ll Learn: JavaScript alerts, confirms and prompts, new tabs and popup windows, native and custom dropdowns, iframes and nested frames, file uploads, hover, right-click, drag and drop, and the Selenium equivalents.


🗂️ Quick Reference

SituationPlaywright API
JavaScript alert, confirm, promptpage.on(‘dialog’) / page.once(‘dialog’)
Link opens a new tab or popup windowpage.waitForEvent(‘popup’)
Any new page in the browser contextcontext.waitForEvent(‘page’)
Native select dropdownlocator.selectOption()
Custom (div-based) dropdownclick, then getByRole(‘option’)
Element inside an iframepage.frameLocator() or locator.contentFrame()
File uploadlocator.setInputFiles() or the filechooser event
Mouse hover, right-click, drag and drophover(), click({ button: ‘right’ }), dragTo()

All examples below use the free practice site the-internet.herokuapp.com, so you can copy them and run them yourself. You can also practise on the SQA Tools automation practice pages.


🔔 Handle Alerts, Confirms and Prompts (Dialogs)

JavaScript dialogs (alert(), confirm(), prompt() and beforeunload) block the page. By default Playwright dismisses them automatically, so a confirm returns “Cancel”. To accept a dialog, read its message or type into a prompt, register a handler before the action that opens it.

Accept an alert and read its message

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

test('accept a JS alert', async ({ page }) => {
  await page.goto('https://the-internet.herokuapp.com/javascript_alerts');

  page.once('dialog', async dialog => {
    expect(dialog.type()).toBe('alert');
    expect(dialog.message()).toBe('I am a JS Alert');
    await dialog.accept();
  });

  await page.getByRole('button', { name: 'Click for JS Alert' }).click();
  await expect(page.locator('#result')).toHaveText('You successfully clicked an alert');
});

Accept or dismiss a confirm

test('dismiss a confirm', async ({ page }) => {
  await page.goto('https://the-internet.herokuapp.com/javascript_alerts');

  page.once('dialog', dialog => dialog.dismiss()); // click "Cancel"
  await page.getByRole('button', { name: 'Click for JS Confirm' }).click();
  await expect(page.locator('#result')).toHaveText('You clicked: Cancel');
});

Type into a prompt

test('answer a prompt', async ({ page }) => {
  await page.goto('https://the-internet.herokuapp.com/javascript_alerts');

  page.once('dialog', dialog => dialog.accept('Playwright'));
  await page.getByRole('button', { name: 'Click for JS Prompt' }).click();
  await expect(page.locator('#result')).toHaveText('You entered: Playwright');
});

⚠️ Common mistake: Use page.once for a single dialog. With page.on the handler stays active for the rest of the test, and a handler that neither accepts nor dismisses the dialog will make the next action hang.

📝 Note: Website modals built with HTML (cookie banners, “subscribe” overlays) are not dialogs. Handle them like normal elements: await page.getByRole('button', { name: 'Accept' }).click().


🪟 Handle a New Tab or Popup Window

When a link opens a new tab (target="_blank") or window.open() creates a popup, wait for the popup event. Start waiting before the click, then work with the new page object.

test('work with a new tab', async ({ page }) => {
  await page.goto('https://the-internet.herokuapp.com/windows');

  const popupPromise = page.waitForEvent('popup');      // 1. start listening
  await page.getByRole('link', { name: 'Click Here' }).click(); // 2. open it
  const newTab = await popupPromise;                    // 3. get the new page

  await newTab.waitForLoadState();
  await expect(newTab.locator('h3')).toHaveText('New Window');

  // Switch back: just use the original page object again
  await expect(page.locator('h3')).toHaveText('Opening a new window');
  await newTab.close();
});

There is no “switch to window” step like in Selenium: each tab is a separate Page object, and you simply call methods on the one you need.

Track any new page in the context

const pagePromise = page.context().waitForEvent('page');
await page.getByRole('link', { name: 'Open report' }).click();
const reportPage = await pagePromise;

// List every open tab
for (const p of page.context().pages()) {
  console.log(await p.title());
}

🔽 Select from a Dropdown

Native select elements

For a real <select> element, use selectOption(). You can select by value, label or index, and select several options in a multi-select.

test('select from a dropdown', async ({ page }) => {
  await page.goto('https://the-internet.herokuapp.com/dropdown');
  const dropdown = page.locator('#dropdown');

  await dropdown.selectOption('1');                    // by value
  await expect(dropdown).toHaveValue('1');

  await dropdown.selectOption({ label: 'Option 2' });  // by visible text
  await expect(dropdown).toHaveValue('2');

  await dropdown.selectOption({ index: 1 });           // by position
});

// Multi-select: pass an array
// await page.locator('#colors').selectOption(['red', 'blue']);

Read all options to verify the list:

const options = await page.locator('#dropdown option').allTextContents();
expect(options).toEqual(['Please select an option', 'Option 1', 'Option 2']);

Custom dropdowns (div or React components)

Many modern apps draw dropdowns with div and li elements. selectOption() does not work on them. Click to open, then click the option, preferably by role.

await page.getByRole('combobox', { name: 'Country' }).click();
await page.getByRole('option', { name: 'India' }).click();
await expect(page.getByRole('combobox', { name: 'Country' })).toHaveText(/India/);

🖼️ Handle iFrames

Elements inside an <iframe> belong to a different document, so normal page locators cannot see them. Use frameLocator() to reach inside. It auto-waits like any locator, and there is no “switch back” step.

// Single iframe, e.g. an embedded payment form
const payment = page.frameLocator('iframe[title="Secure payment"]');
await payment.getByLabel('Card number').fill('4242 4242 4242 4242');
await payment.getByRole('button', { name: 'Pay' }).click();

Nested frames

test('read text from nested frames', async ({ page }) => {
  await page.goto('https://the-internet.herokuapp.com/nested_frames');

  const middle = page
    .frameLocator('frame[name="frame-top"]')
    .frameLocator('frame[name="frame-middle"]');

  await expect(middle.locator('#content')).toHaveText('MIDDLE');
});

From a locator to its frame

In recent Playwright versions you can also go from an iframe element to its content with contentFrame():

const frame = page.locator('#editor-frame').contentFrame();
await frame.locator('body').fill('Hello from Playwright');

💡 Tip: Need the full Frame object (for example to run evaluate)? Use page.frame({ name: 'frame-name' }) or page.frame({ url: /checkout/ }).


📤 Upload Files

For a normal <input type="file">, call setInputFiles(). It works even when the input is hidden.

import path from 'path';

test('upload a file', async ({ page }) => {
  await page.goto('https://the-internet.herokuapp.com/upload');

  await page.locator('#file-upload').setInputFiles(path.join(__dirname, 'data', 'sample.txt'));
  await page.locator('#file-submit').click();

  await expect(page.locator('#uploaded-files')).toHaveText('sample.txt');
});

// Multiple files:  setInputFiles(['a.png', 'b.png'])
// Clear the input: setInputFiles([])

If the page opens the file picker from a custom button, wait for the filechooser event:

const chooserPromise = page.waitForEvent('filechooser');
await page.getByRole('button', { name: 'Upload resume' }).click();
const chooser = await chooserPromise;
await chooser.setFiles('data/resume.pdf');

For downloads, see how to perform file downloads in Playwright.


🖱️ Mouse Hover, Right-Click, Double-Click and Drag and Drop

// Hover to reveal a hidden menu or caption
await page.goto('https://the-internet.herokuapp.com/hovers');
await page.locator('.figure').first().hover();
await expect(page.getByText('name: user1')).toBeVisible();

// Right-click and double-click
await page.locator('#hot-spot').click({ button: 'right' });
await page.getByText('Edit').dblclick();

// Drag and drop
await page.goto('https://the-internet.herokuapp.com/drag_and_drop');
await page.locator('#column-a').dragTo(page.locator('#column-b'));
await expect(page.locator('#column-a header')).toHaveText('B');

// Keyboard
await page.getByLabel('Search').press('Enter');
await page.keyboard.press('Control+A');

🔄 Selenium vs Playwright for These Scenarios

TaskSeleniumPlaywright
Alertdriver.switchTo().alert().accept()page.once(‘dialog’, d => d.accept())
New windowgetWindowHandles() then switchTo().window()page.waitForEvent(‘popup’)
Dropdownnew Select(el).selectByVisibleText()selectOption({ label })
iFrameswitchTo().frame() then defaultContent()page.frameLocator()
Hovernew Actions(driver).moveToElement(el)locator.hover()

Compare with our Python Selenium guides for alerts, dropdowns and iframes, or read the full Playwright vs Selenium vs Cypress comparison.


✅ Best Practices

  • Register dialog handlers and start waitForEvent promises before the click that triggers them.
  • Prefer page.once over page.on for one-off dialogs.
  • Keep a separate Page variable for each tab; close tabs you no longer need.
  • Use frameLocator with a stable selector (title, name or id) for the iframe.
  • Use role-based locators for custom dropdowns, and selectOption only for native selects.

❓ FAQ

🤔 How do I handle a popup in Playwright?

For a new tab or window, use const popup = await page.waitForEvent('popup') (start it before the click). For a JavaScript alert, use page.once('dialog', d => d.accept()). For an HTML modal, click its buttons like any other element.

🤔 Why does Playwright close my alert automatically?

Playwright dismisses dialogs by default so tests never hang. Add a dialog handler to accept it, read the message or enter prompt text.

🤔 How do I select a value from a dropdown in Playwright?

Use await page.locator('select#id').selectOption({ label: 'Option text' }) for native selects. For custom dropdowns, click the control and then page.getByRole('option', { name: '...' }).click().

🤔 How do I switch to an iframe in Playwright?

You do not switch. Create a frame locator, page.frameLocator('iframe#id'), and use locators on it. The main page stays available through page.

🤔 How do I switch between tabs in Playwright?

Every tab is its own Page object. Keep references (for example page and newTab) and call methods on the one you need; context.pages() lists all open tabs.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright Waits Explained: Auto-Waiting, waitFor, waitForLoadState, waitForResponse and Timeouts

Flaky tests are almost always waiting problems. Playwright solves most of them with auto-waiting, but you still need to know when and how to wait for elements, pages, URLs and API responses. This guide explains every Playwright wait method with TypeScript examples and clear advice on which one to use.

📖 What You’ll Learn: auto-waiting and actionability checks, web-first assertions, locator.waitFor, waitForLoadState, waitForURL, waitForResponse, why to avoid waitForTimeout and networkidle, waitForFunction, expect.poll, toPass, timeouts and troubleshooting.


🤖 Auto-Waiting: Why You Rarely Need Manual Waits

The biggest difference between Playwright and older tools is auto-waiting. Before every action, Playwright waits until the element is ready, so you do not write sleeps or explicit waits for normal clicks and typing.

Before click(), for example, Playwright checks that the element is:

  • Attached to the page (it exists in the DOM)
  • Visible (not hidden, has a size)
  • Stable (not moving or animating)
  • Receives events (not covered by another element such as a loader)
  • Enabled (not disabled)

fill() additionally waits until the field is editable. If the checks do not pass within the timeout, the action fails with a clear error explaining which check failed.

// No waits needed: Playwright waits for the button to be ready
await page.getByRole('button', { name: 'Login' }).click();
await page.getByLabel('Email').fill('qa@sqatools.in');

💡 Tip: Most “wait” problems in Playwright disappear once you use locators (page.getByRole, page.locator) and web-first assertions (await expect(...)). Reach for the methods below only for special cases.


✅ Web-First Assertions: The Best Way to Wait

Assertions such as toBeVisible(), toHaveText() and toHaveURL() retry automatically until the condition is true or the timeout (5 seconds by default) expires. They are the cleanest way to wait for a result.

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

test('order confirmation appears', async ({ page }) => {
  await page.goto('https://www.saucedemo.com/');
  // ...log in and place an order...

  // Waits up to 5 s (default) for the element and the text
  await expect(page.getByText('Thank you for your order!')).toBeVisible();

  // Custom timeout for a slow step
  await expect(page.locator('.complete-header')).toHaveText('Thank you for your order!', { timeout: 15_000 });

  // Wait for an element to disappear
  await expect(page.locator('.loading-spinner')).toBeHidden();
});

⚠️ Common mistake: Do not write expect(await locator.isVisible()).toBe(true). isVisible() checks once and does not wait. Use await expect(locator).toBeVisible() instead.


👁️ Wait for an Element to Be Visible: locator.waitFor()

When you need to wait for an element without asserting (for example inside a helper), use locator.waitFor() with a state.

const toast = page.locator('.toast-message');

await toast.waitFor();                       // default state: 'visible'
await toast.waitFor({ state: 'hidden' });    // wait until it disappears
await toast.waitFor({ state: 'attached' });  // exists in the DOM (may be hidden)
await toast.waitFor({ state: 'detached', timeout: 10_000 }); // removed from the DOM

🌐 Wait for the Page to Load: waitForLoadState()

page.goto() already waits for the load event by default. Use waitForLoadState() when the page loads after an action, such as a click that triggers a navigation, or when you need a different state.

StateMeaning
loadThe load event fired (all resources such as images loaded). Default for goto.
domcontentloadedHTML parsed; images and styles may still be loading.
networkidleNo network requests for at least 500 ms. Discouraged.
await page.goto('https://sqatools.in', { waitUntil: 'domcontentloaded' });

await page.getByRole('link', { name: 'Blog' }).click();
await page.waitForLoadState('domcontentloaded');

⚠️ Common mistake: networkidle is a common way to “wait for network idle”, but Playwright discourages it: pages with analytics, polling or live chat may never become idle, which makes tests slow or flaky. Wait for the specific element or response you care about instead.


🔗 Wait for a URL: waitForURL()

After a click that navigates, wait for the new URL. waitForNavigation() is deprecated; use waitForURL() or the toHaveURL() assertion.

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

await page.waitForURL('**/inventory.html');   // glob pattern
await page.waitForURL(/inventory/);           // regular expression

// Or as an assertion (also retries)
await expect(page).toHaveURL(/inventory/);

📡 Wait for an API Response: waitForResponse()

Many modern pages load data with API calls. Wait for the exact response, then check its data. Start waiting before the action that triggers the request, otherwise you can miss a fast response.

// 1. Start listening first (no await yet)
const responsePromise = page.waitForResponse(resp =>
  resp.url().includes('/api/products') && resp.status() === 200
);

// 2. Trigger the request
await page.getByRole('button', { name: 'Search' }).click();

// 3. Now await the response
const response = await responsePromise;
const data = await response.json();
expect(data.items.length).toBeGreaterThan(0);

The same pattern works for page.waitForRequest() and other events, such as page.waitForEvent('download') and page.waitForEvent('popup').


⏱️ Wait for 5 Seconds: waitForTimeout() (and Why to Avoid It)

You can pause a test for a fixed time:

await page.waitForTimeout(5000); // waits 5 seconds

This is a hard wait. It makes tests slower when the app is fast and still flaky when the app is slower than expected. Playwright’s documentation says it should be used only for debugging. Replace it with a condition:

Instead ofUse
waitForTimeout after a clickexpect(locator).toBeVisible()
waitForTimeout for a spinnerexpect(spinner).toBeHidden()
waitForTimeout for data to loadpage.waitForResponse(…)
waitForTimeout for navigationpage.waitForURL(…)

🔁 Custom Conditions: waitForFunction, expect.poll and toPass

page.waitForFunction()

Runs a function in the browser repeatedly until it returns a truthy value.

await page.waitForFunction(() => document.querySelectorAll('.inventory_item').length >= 6);

expect.poll()

Retries any Node.js function, for example an API call, until the assertion passes.

await expect.poll(async () => {
  const res = await page.request.get('https://api.example.com/jobs/42');
  return (await res.json()).status;
}, { timeout: 30_000, intervals: [1_000, 2_000, 5_000] }).toBe('COMPLETED');

expect(…).toPass()

Retries a whole block of steps until all of them pass.

await expect(async () => {
  await page.getByRole('button', { name: 'Refresh' }).click();
  await expect(page.getByText('Report ready')).toBeVisible({ timeout: 1_000 });
}).toPass({ timeout: 20_000 });

⚙️ Timeouts: Defaults and How to Change Them

TimeoutDefaultWhere to change
Test timeout30 secondstimeout in config, test.setTimeout()
Assertion (expect) timeout5 secondsexpect: { timeout } in config, or per assertion
Action timeout (click, fill)No limit (bounded by the test timeout)use: { actionTimeout }
Navigation timeout (goto, waitForURL)No limit (bounded by the test timeout)use: { navigationTimeout }
// playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  timeout: 60_000,               // each test may run 60 s
  expect: { timeout: 10_000 },   // each assertion waits up to 10 s
  use: {
    actionTimeout: 15_000,       // each click/fill waits up to 15 s
    navigationTimeout: 30_000,   // each goto waits up to 30 s
  },
});
// For one slow test
test('generate yearly report', async ({ page }) => {
  test.slow();               // triples the timeout
  // or: test.setTimeout(120_000);
});

Learn more about config in maintaining multiple config files.


🧹 Legacy Methods You May See in Old Code

  • page.waitForSelector(): still works, but the docs recommend locators with waitFor() or assertions.
  • page.waitForNavigation(): deprecated; use waitForURL().
  • page.waitForTimeout(): only for debugging.

🐞 Troubleshooting Timeout Errors

  • “Timeout 30000ms exceeded” on an action: the element never became actionable. Run with npx playwright test --ui or open the trace to see whether it was hidden, covered or disabled.
  • Element is covered by another element: wait for the overlay or spinner to disappear with expect(overlay).toBeHidden().
  • Strict mode violation: your locator matched several elements. Make it more specific; see Playwright locators.
  • Test passes locally but fails in CI: CI machines are slower. Prefer condition-based waits and enable trace: 'on-first-retry' to inspect failures.

✅ Best Practices

  • Trust auto-waiting; do not add waits before normal actions.
  • Use web-first assertions as your main waiting tool.
  • Start waitForResponse and waitForEvent promises before the triggering action.
  • Avoid waitForTimeout and networkidle in real tests.
  • Increase timeouts for specific slow steps instead of globally.

❓ FAQ

🤔 How do I wait for an element to be visible in Playwright?

Use await expect(locator).toBeVisible() in tests, or await locator.waitFor({ state: 'visible' }) in helper code. Both wait automatically up to the timeout.

🤔 How do I wait for a page to load in Playwright?

page.goto() waits for the load event by default. After a click, use page.waitForURL() or page.waitForLoadState(), or simply assert on an element of the new page.

🤔 How do I wait for 5 seconds in Playwright?

await page.waitForTimeout(5000). Use it only while debugging; in real tests wait for a condition instead.

🤔 Does Playwright have implicit waits like Selenium?

Not as a setting. Playwright’s auto-waiting is applied automatically to every action and web-first assertion, which replaces implicit waits. Compare with Selenium waits.

🤔 What is the default timeout in Playwright?

30 seconds per test and 5 seconds per expect assertion. Actions and navigations have no separate limit by default, so they are bounded by the test timeout.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright vs Selenium vs Cypress: Which Should You Choose in 2026?

Playwright, Selenium and Cypress are the three most popular web test automation tools, and choosing between them is one of the first decisions every QA team makes. This guide compares them side by side, shows the same test written in each, and gives a clear recommendation for different situations.

📖 What You’ll Learn: what each tool is, a full feature comparison table, architecture differences, the same login test in all three, which is easier to learn, job trends, a Selenium to Playwright concept map, and pros and cons.


⚡ Quick Answer

  • Choose Playwright for new web automation projects: fast setup, automatic waiting, built-in parallel runs, API testing and excellent debugging tools, all free.
  • Choose Selenium when you need a language Playwright does not support (such as Ruby or PHP), real Safari on macOS through WebDriver, legacy browsers, or you already have a large Selenium suite and Grid.
  • Choose Cypress for a JavaScript-only team that mainly tests a single front-end app and wants an interactive, in-browser runner, and that does not need multiple tabs or several browser windows in one test.

🧭 What Each Tool Is

Playwright

An open-source end-to-end testing framework released by Microsoft in 2020, built by engineers who previously created Puppeteer. One API controls Chromium, Firefox and WebKit. It ships with its own test runner (@playwright/test), assertions, reporters, codegen, UI mode and Trace Viewer.

Selenium

The original browser automation project, started in 2004. Selenium WebDriver became the W3C WebDriver standard that browser vendors implement. Selenium is a library, not a full framework: you combine it with a test runner such as TestNG, JUnit or pytest, and with Selenium Grid for distributed runs.

Cypress

A JavaScript testing tool launched around 2017 that runs inside the browser, next to your application. It is known for its interactive runner with time-travel snapshots and is popular with front-end developers.


📊 Feature Comparison Table

FeaturePlaywrightSeleniumCypress
First released202020042017
LanguagesJavaScript, TypeScript, Python, Java, .NETJava, Python, C#, JavaScript, Ruby, Kotlin and moreJavaScript, TypeScript
BrowsersChromium (Chrome, Edge), Firefox, WebKitChrome, Edge, Firefox, Safari, IE modeChrome-family, Firefox, Electron; WebKit experimental
ArchitectureTalks to browsers over a WebSocket connectionW3C WebDriver protocol through browser driversRuns inside the browser with the app
Test runnerBuilt inBring your own (TestNG, JUnit, pytest)Built in
WaitingAutomatic actionability checksExplicit and implicit waitsAutomatic retries
Multiple tabs and windowsYesYesNo
Cross-origin navigationYesYesLimited, needs cy.origin
iFramesSimple with frameLocatorswitchTo().frameWorkarounds needed
Parallel executionBuilt in and free (workers, sharding)Selenium Grid or runner pluginsCypress Cloud (paid) or third-party tools
API testingBuilt in (request fixture)Needs another librarycy.request
Network mockingpage.routeLimited (BiDi / CDP)cy.intercept
DebuggingTrace Viewer, UI mode, Inspector, codegenLogs, screenshots, IDE debuggerTime-travel runner, DevTools
MobileBrowser emulation of devicesReal devices via AppiumViewport resizing
CostFree, Apache 2.0Free, Apache 2.0Free runner, paid cloud

🏗️ Architecture Differences (Why Playwright Feels Faster)

Selenium sends each command (click, type, find) as an HTTP request to a browser driver such as ChromeDriver, which then controls the browser. Every step is a separate round trip, and your code must wait explicitly for elements to be ready.

Playwright keeps one persistent WebSocket connection open to the browser and sends commands over it. Before every action it automatically checks that the element is attached, visible, stable, enabled and able to receive events. Each test also gets a fresh browser context, which is like a brand-new incognito profile that starts in milliseconds, so tests are isolated without restarting the browser.

Cypress injects your test code into the browser itself. This gives it direct access to the app and a great live view, but it is also why it cannot drive two tabs or two browsers at once.

📝 Note: Selenium 4 added WebDriver BiDi and Chrome DevTools support, which narrows some gaps (such as network events). Playwright’s advantages in setup, waiting and tooling are still significant for most teams.


🧑‍💻 The Same Test in All Three Tools

A login test on the Sauce Demo site, to compare how much code and waiting each needs.

Playwright (TypeScript)

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

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

Selenium (Python)

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("https://www.saucedemo.com/")
driver.find_element(By.ID, "user-name").send_keys("standard_user")
driver.find_element(By.ID, "password").send_keys("secret_sauce")
driver.find_element(By.ID, "login-button").click()

title = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.CLASS_NAME, "title"))
)
assert title.text == "Products"
driver.quit()

Cypress (JavaScript)

describe('login', () => {
  it('logs in', () => {
    cy.visit('https://www.saucedemo.com/');
    cy.get('[data-test="username"]').type('standard_user');
    cy.get('[data-test="password"]').type('secret_sauce');
    cy.get('[data-test="login-button"]').click();
    cy.get('.title').should('have.text', 'Products');
  });
});

Notice that Playwright and Cypress need no explicit wait, while Selenium uses WebDriverWait for the final check. Playwright also needs no driver management or separate runner configuration.


📈 Which Is Easier to Learn?

For beginners, Playwright and Cypress are easier to start with than Selenium: one install command, a built-in runner and automatic waiting remove the most common causes of flaky tests. Between the two, Playwright is more flexible once you go beyond basic UI flows (multiple tabs, iframes, API tests, several browsers), while Cypress has the gentlest first hour thanks to its visual runner.

Selenium has a steeper start because you assemble the framework yourself (driver, runner, waits, reporting), but it teaches concepts that apply everywhere, and its language support is the widest.


💼 Jobs and Industry Trend

Selenium still appears in a very large number of job descriptions because of the huge number of existing suites. Playwright has grown the fastest of the three in recent years (in npm downloads, GitHub stars and job mentions), and many teams now choose it for new projects or migrate to it. Learning Playwright with TypeScript, while understanding Selenium concepts, is a strong combination for QA automation roles in 2026.


🔄 Moving from Selenium to Playwright: Concept Map

SeleniumPlaywright
driver.get(url)page.goto(url)
driver.findElement(By.id(‘x’))page.locator(‘#x’) or page.getByRole(…)
sendKeys(‘text’)fill(‘text’)
WebDriverWait + ExpectedConditionsAuto-waiting and expect(locator).toBeVisible()
new Select(el).selectByVisibleText(‘A’)locator.selectOption({ label: ‘A’ })
driver.switchTo().frame(‘f’)page.frameLocator(‘#f’)
driver.switchTo().alert().accept()page.on(‘dialog’, d => d.accept())
getWindowHandles() and switchTo().window()page.waitForEvent(‘popup’)
Actions(driver).moveToElement(el)locator.hover()
Selenium GridBuilt-in workers and –shard

Want practical examples? See Playwright waits explained and handling alerts, popups, iframes and tabs in Playwright. If you are coming from Python Selenium, compare with our Selenium waits and Selenium locators guides.


⚖️ Pros and Cons Summary

Playwright

  • ✅ Fast, reliable auto-waiting; free parallel runs; API testing and network mocking built in
  • ✅ Best-in-class debugging with Trace Viewer, UI mode and codegen
  • ❌ Uses its own builds of Firefox and WebKit rather than the exact branded Safari; no native mobile app testing

Selenium

  • ✅ Widest language and browser support, W3C standard, huge community
  • ✅ Real mobile testing through Appium and mature Grid infrastructure
  • ❌ More boilerplate, manual waits, and you must assemble the framework yourself

Cypress

  • ✅ Very friendly interactive runner and great developer experience
  • ✅ Strong for front-end and component testing
  • ❌ JavaScript only, no multi-tab support, parallel runs mainly through a paid cloud

❓ FAQ

🤔 Is Playwright better than Selenium?

For most new web projects, yes: it is faster to set up, less flaky and includes more built-in features. Selenium remains better when you need its languages, real branded browsers through WebDriver, Appium mobile testing or an existing Grid.

🤔 Is Playwright faster than Selenium?

Usually yes. A persistent connection, lightweight browser contexts and automatic waiting reduce overhead and retries. Actual speed depends on your application and test design.

🤔 Should I learn Selenium or Playwright in 2026?

If you are starting fresh, learn Playwright with TypeScript first, then learn Selenium concepts so you can work on existing suites. Both skills appear in job descriptions.

🤔 Can Playwright replace Cypress?

Yes for end-to-end testing. Playwright covers everything Cypress does for E2E plus multiple tabs, more browsers and free parallelism. Some teams keep Cypress specifically for component testing.

🤔 Does Playwright support Safari?

Playwright tests WebKit, the engine behind Safari, on Windows, macOS and Linux. It does not drive the branded Safari app itself; Selenium with safaridriver does.


🎯 Next Steps

🎬 Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

TypeScript for Playwright: Complete Beginner Tutorial (Setup, Concepts and Framework)

This is the bridge between learning TypeScript and building real Playwright automation. You will set up a Playwright TypeScript project, learn exactly which TypeScript concepts matter for testing, and build typed tests, page objects and fixtures step by step.

📖 What You’ll Learn: why TypeScript for Playwright, the concepts you need, project setup, playwright.config.ts, async/await and Promise, Page and Locator types, typed test data, page object classes, generic fixtures, type checking with tsc, and common errors.


🎯 Why Use TypeScript with Playwright?

Playwright supports JavaScript, TypeScript, Python, Java and .NET, but TypeScript is the most popular choice for Playwright projects, and it is what the official documentation uses in its examples. The reasons are practical:

  • Autocomplete everywhere: type page. and your editor lists every method with its parameters.
  • Errors before you run: a typo like page.gotoo() or a missing await on a typed value is flagged instantly.
  • Zero setup: Playwright runs .ts test files directly; you do not need to configure a separate compiler.
  • Safer refactoring: rename a page object method and every usage is updated or highlighted.
  • Better job prospects: “Playwright + TypeScript” is one of the most requested combinations in QA automation job posts.

🗺️ TypeScript Concepts You Need for Playwright

You do not need to master all of TypeScript before writing tests. This is the practical checklist, in learning order, with a guide for each:

ConceptWhere you use it in PlaywrightGuide
Variables and data typesTest data, URLs, timeoutsVariables, Data Types
Conditions and loopsData-driven tests, retriesConditions, Loops
Functions and async/awaitEvery test and helperFunctions
ArraysLists of elements and test casesArrays
ObjectsTest data, config, API payloadsObjects
Interfaces and typesTyped data and API responsesInterfaces
ClassesPage Object ModelClasses
GenericsFixtures, API helpersGenerics

💡 Tip: If you are completely new, learn variables, functions, async/await, arrays and objects first. That is enough to write real Playwright tests. Add interfaces, classes and generics when you start building a framework.


⚙️ Step 1: Set Up a Playwright TypeScript Project

You need Node.js (LTS version) and VS Code. Then run one command in an empty folder:

npm init playwright@latest

Choose TypeScript when asked, accept the default tests folder, add a GitHub Actions workflow if you want CI, and let it install the browsers. Then install the official Playwright Test for VS Code extension to run and debug tests from the editor.

The generated project looks like this:

my-project/
├── tests/
│   └── example.spec.ts      # your tests
├── playwright.config.ts     # Playwright settings (typed!)
├── package.json
└── package-lock.json

🛠️ Step 2: Understand playwright.config.ts

The config file is plain TypeScript. defineConfig gives you autocomplete and type checking for every option.

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

export default defineConfig({
  testDir: './tests',
  timeout: 30_000,               // max time per test (ms)
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 2 : undefined,
  reporter: [['html', { open: 'never' }]],
  use: {
    baseURL: 'https://www.saucedemo.com',
    trace: 'on-first-retry',     // record a trace when a test is retried
    screenshot: 'only-on-failure',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox',  use: { ...devices['Desktop Firefox'] } },
  ],
});

📝 Note: Because of the types, a misspelled option such as retires: 2 is underlined in red immediately instead of being silently ignored.


✍️ Step 3: Your First TypeScript Test

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

test('valid user can log in', async ({ page }) => {
  await page.goto('/');                                   // uses baseURL
  await page.getByPlaceholder('Username').fill('standard_user');
  await page.getByPlaceholder('Password').fill('secret_sauce');
  await page.getByRole('button', { name: 'Login' }).click();

  await expect(page).toHaveURL(/inventory/);
  await expect(page.locator('.title')).toHaveText('Products');
});

Run it:

npx playwright test                 # run all tests headless
npx playwright test --ui            # interactive UI mode
npx playwright test login.spec.ts   # run one file
npx playwright show-report          # open the HTML report

⏳ async, await and Promise<T>

Almost every Playwright action talks to the browser, so it returns a Promise. Always put await in front, otherwise the next line runs before the action finishes.

// ✅ correct
await page.getByRole('button', { name: 'Login' }).click();

// ❌ missing await: the test may finish before the click happens
page.getByRole('button', { name: 'Login' }).click();

// Helper functions return Promise<T>
async function getCartCount(page: Page): Promise<number> {
  const text = await page.locator('.shopping_cart_badge').textContent();
  return Number(text ?? 0);
}

⚠️ Common mistake: A missing await is the number one cause of flaky Playwright tests. Enable the ESLint rule @typescript-eslint/no-floating-promises to catch it automatically.


🏷️ The Playwright Types You Will Use Most

Import these from @playwright/test to type your helpers and page objects:

TypeWhat it represents
PageA browser tab
LocatorA way to find element(s) on the page
BrowserContextAn isolated browser session (cookies, storage)
APIRequestContextThe client for API tests (request fixture)
TestInfoDetails about the running test (title, retries, attachments)
expectThe assertion function
import { Page, Locator, expect } from '@playwright/test';

async function addToCart(page: Page, productName: string): Promise<void> {
  const item: Locator = page.locator('.inventory_item').filter({ hasText: productName });
  await item.getByRole('button', { name: 'Add to cart' }).click();
  await expect(page.locator('.shopping_cart_badge')).toBeVisible();
}

📦 Typing Test Data

Use interfaces and union types so wrong test data is impossible to write.

// test-data/users.ts
export type Role = 'standard' | 'locked' | 'problem';

export interface TestUser {
  username: string;
  password: string;
  canLogin: boolean;
}

export const USERS: Record<Role, TestUser> = {
  standard: { username: 'standard_user',   password: 'secret_sauce', canLogin: true },
  locked:   { username: 'locked_out_user', password: 'secret_sauce', canLogin: false },
  problem:  { username: 'problem_user',    password: 'secret_sauce', canLogin: true },
};
// tests/users.spec.ts
import { test, expect } from '@playwright/test';
import { USERS } from '../test-data/users';

for (const [role, user] of Object.entries(USERS)) {
  test('login behaviour for ' + role + ' user', async ({ page }) => {
    await page.goto('/');
    await page.getByPlaceholder('Username').fill(user.username);
    await page.getByPlaceholder('Password').fill(user.password);
    await page.getByRole('button', { name: 'Login' }).click();

    if (user.canLogin) {
      await expect(page).toHaveURL(/inventory/);
    } else {
      await expect(page.locator('[data-test="error"]')).toBeVisible();
    }
  });
}

🏛️ Page Objects with Classes

As tests grow, move locators and actions into classes. This is the Page Object Model:

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

export class InventoryPage {
  readonly title: Locator;
  readonly cartBadge: Locator;

  constructor(private readonly page: Page) {
    this.title = page.locator('.title');
    this.cartBadge = page.locator('.shopping_cart_badge');
  }

  async addItem(name: string): Promise<void> {
    await this.page.locator('.inventory_item').filter({ hasText: name })
      .getByRole('button', { name: 'Add to cart' }).click();
  }

  async expectCartCount(count: number): Promise<void> {
    await expect(this.cartBadge).toHaveText(String(count));
  }
}

Full walkthrough: Playwright Page Object Model step by step.


🧩 Typed Fixtures with Generics

Custom fixtures inject ready-made page objects into every test. test.extend<T>() is a generic, so each fixture is fully typed.

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

type Pages = { inventoryPage: InventoryPage };

export const test = base.extend<Pages>({
  inventoryPage: async ({ page }, use) => {
    await use(new InventoryPage(page));
  },
});
export { expect } from '@playwright/test';
// tests/cart.spec.ts
import { test } from '../fixtures';

test('add two items to the cart', async ({ page, inventoryPage }) => {
  // log in first (or reuse a saved session with storageState)
  await inventoryPage.addItem('Sauce Labs Backpack');
  await inventoryPage.addItem('Sauce Labs Bike Light');
  await inventoryPage.expectCartCount(2);
});

🔍 Important: Playwright Does Not Type-Check Your Tests

Playwright transpiles TypeScript so it can run it fast, but it does not report type errors when you run npx playwright test. Your editor shows them, but a CI run can still pass with type errors. Add a type-check step:

npx tsc --noEmit

Add a minimal tsconfig.json if your project does not have one:

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "noEmit": true
  },
  "include": ["tests", "pages", "test-data", "*.ts"]
}

💡 Tip: Run npx tsc --noEmit before npx playwright test in your GitHub Actions pipeline so type errors fail the build early.


🐞 Common TypeScript Errors in Playwright (and Fixes)

Error messageCauseFix
Object is possibly ‘null’textContent() can return nullUse ?? '' or assert with toHaveText
Property ‘x’ does not exist on typeTypo or missing property in a typeFix the name or add it to the interface
‘await’ expressions are only allowed within async functionsMissing asyncAdd async before the function
Cannot find module ‘../pages/LoginPage’Wrong relative pathCheck the path and file name casing
Argument of type ‘string or undefined’Reading process.envProvide a default: process.env.BASE_URL ?? 'https://...'

🚀 Recommended Learning Path

  1. Learn the TypeScript basics from the table above (1 to 2 weeks).
  2. Write simple tests with locators and assertions: Locators, Assertions.
  3. Learn fixtures and annotations.
  4. Build a framework with the Page Object Model and external test data (JSON, CSV, .env).
  5. Complete the beginner automation project.
  6. Prepare with 200 Playwright + TypeScript interview questions.

❓ FAQ

🤔 Do I need to learn TypeScript before Playwright?

You need the basics: variables, functions, async/await, arrays and objects. You can learn interfaces, classes and generics while building your first framework.

🤔 Is TypeScript or JavaScript better for Playwright?

TypeScript is recommended. It runs with zero extra setup, gives autocomplete and catches mistakes before tests run. JavaScript works too, but large suites are harder to maintain.

🤔 How long does it take to learn TypeScript for Playwright?

Most testers with basic programming knowledge are productive in 2 to 4 weeks of regular practice, following the learning path above.

🤔 Does Playwright check TypeScript types when running tests?

No. Playwright only transpiles TypeScript. Run npx tsc --noEmit separately (locally and in CI) to catch type errors.

🤔 Which TypeScript version does Playwright need?

Playwright bundles its own TypeScript transpiler, so you do not need to install TypeScript to run tests. Install the typescript package only for tsc type checking and editor tooling.


🎯 Next Steps

🎬 Watch the full TypeScript tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

TypeScript Generics Explained for Beginners (with Examples and Playwright Use Cases)

Generics sound advanced, but the idea is simple: write code once and let it work safely with any type. This guide explains TypeScript generics step by step for beginners, with clear examples and the places you already meet them in Playwright.

📖 What You’ll Learn: what generics are, generic functions and arrow functions, multiple type parameters, constraints with extends and keyof, generic interfaces and classes, utility types like Partial and Omit, and generics in Playwright fixtures and API helpers.


🧪 What Are Generics? (Explained Simply)

Generics let you write code that works with many types while still keeping full type safety. You write the logic once and leave a “blank” for the type. The blank is filled in when the code is used.

A useful analogy is a labelled storage box. The box works the same whether it holds books or shoes, but once you write “Books” on the label, you can only put books in it and you know you will get books out. In TypeScript that label is the type parameter, usually written <T>.


🤔 The Problem Generics Solve

Imagine a function that returns the first item of an array. Without generics you have two bad options:

// Option 1: one function per type (repetitive)
function firstString(items: string[]): string { return items[0]; }
function firstNumber(items: number[]): number { return items[0]; }

// Option 2: use any (no type safety)
function firstAny(items: any[]): any { return items[0]; }

const value = firstAny(['chromium', 'firefox']);
value.toFixed(2); // ❌ no error in the editor, but crashes at runtime!

✨ Your First Generic Function

Add <T> after the function name. T is a placeholder for “whatever type the caller uses”.

function first<T>(items: T[]): T {
  return items[0];
}

const browser = first(['chromium', 'firefox']); // T is string, so browser: string
const score = first([90, 85, 70]);              // T is number, so score: number

browser.toUpperCase(); // ✅ string method allowed
// browser.toFixed(2); // ❌ Error: toFixed does not exist on type string

TypeScript usually infers T from the arguments. You can also pass it explicitly: first<string>(['a', 'b']).

💡 Tip: T is just a convention (for “Type”). Other common names are K (key), V (value) and E (element). Descriptive names like TData are fine too.


➡️ Generic Arrow Functions

Arrow functions use the same idea; the <T> goes before the parameters.

const last = <T>(items: T[]): T => items[items.length - 1];

const wrapInArray = <T>(value: T): T[] => [value];

last(['login', 'checkout', 'logout']); // 'logout'
wrapInArray(42);                       // [42]

📝 Note: In .tsx files, write <T,> (with a comma) so the compiler does not confuse it with a JSX tag.


🔢 Multiple Type Parameters

function pair<K, V>(key: K, value: V): [K, V] {
  return [key, value];
}

const p1 = pair('timeout', 30000); // [string, number]
const p2 = pair(1, true);          // [number, boolean]

function mapValues<T, R>(items: T[], fn: (item: T) => R): R[] {
  return items.map(fn);
}

const lengths = mapValues(['a', 'abc'], s => s.length); // number[]

🚧 Generic Constraints with extends

Sometimes T should not be “anything”. A constraint says “T must have at least these properties”. Use extends for that.

// T must have a length property
function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}

longest('playwright', 'ts');  // ✅ strings have length
longest([1, 2, 3], [1]);      // ✅ arrays have length
// longest(10, 20);           // ❌ Error: number has no length

A very common constraint is K extends keyof T, which means “K must be one of the property names of T”.

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const user = { name: 'Deepesh', role: 'SDET', years: 8 };

getProperty(user, 'name');   // string
getProperty(user, 'years');  // number
// getProperty(user, 'email'); // ❌ Error: 'email' is not a key of user

📦 Generic Interfaces and Types

Generics are especially powerful in interfaces. A classic example is a wrapper for API responses where only the data part changes.

interface ApiResponse<T> {
  status: number;
  message: string;
  data: T;
}

interface User { id: number; name: string }
interface Product { sku: string; price: number }

const userRes: ApiResponse<User> = {
  status: 200, message: 'OK', data: { id: 1, name: 'Asha' },
};

const productsRes: ApiResponse<Product[]> = {
  status: 200, message: 'OK', data: [{ sku: 'LP-01', price: 55000 }],
};

// Default type parameter
type Paginated<T = string> = { page: number; items: T[] };
const tags: Paginated = { page: 1, items: ['smoke', 'regression'] };

🏛️ Generic Classes

Classes can be generic too. This simple typed store keeps test data of one type only.

class DataStore<T> {
  private items: T[] = [];

  add(item: T): void {
    this.items.push(item);
  }

  getAll(): T[] {
    return [...this.items];
  }

  find(predicate: (item: T) => boolean): T | undefined {
    return this.items.find(predicate);
  }
}

const users = new DataStore<{ email: string; active: boolean }>();
users.add({ email: 'a@test.com', active: true });
// users.add('hello'); // ❌ Error: string is not the stored type

const active = users.find(u => u.active);

🧰 Built-in Generic Utility Types

TypeScript ships with ready-made generics you will use every day:

UtilityWhat it doesExample
Array<T>Array of TArray<string>
Promise<T>Async result of TPromise<void>
Partial<T>All properties optionalOverride objects
Required<T>All properties requiredFinal config
Readonly<T>All properties read-onlyConstant test data
Pick<T, K>Keep only some propertiesPick<User, 'name'>
Omit<T, K>Remove some propertiesOmit<User, 'password'>
Record<K, V>Object with keys K and values VRecord<string, number>
interface User { id: number; name: string; email: string; password: string }

type PublicUser = Omit<User, 'password'>;        // no password
type UserUpdate = Partial<Pick<User, 'name' | 'email'>>;

const patch: UserUpdate = { email: 'new@test.com' };

🎭 Generics in Playwright: Real Examples

You already use generics in Playwright, maybe without noticing: every async method returns a Promise<T>, and test.extend<T>() is a generic.

1. A typed API helper

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

export async function getJson<T>(request: APIRequestContext, url: string): Promise<T> {
  const response = await request.get(url);
  expect(response.ok()).toBeTruthy();
  return (await response.json()) as T;
}

// usage in a test
interface Todo { id: number; title: string; completed: boolean }

const todo = await getJson<Todo>(request, 'https://jsonplaceholder.typicode.com/todos/1');
expect(todo.completed).toBe(false); // todo is fully typed

2. Typed custom fixtures with test.extend<T>()

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

type MyFixtures = {
  loginPage: LoginPage;
  testUser: { username: string; password: string };
};

export const test = base.extend<MyFixtures>({
  testUser: async ({}, use) => {
    await use({ username: 'standard_user', password: 'secret_sauce' });
  },
  loginPage: async ({ page }, use) => {
    await use(new LoginPage(page));
  },
});

Learn more in Playwright Custom Fixtures with Examples.

3. A generic test data loader

import fs from 'fs';

export function loadJson<T>(path: string): T {
  return JSON.parse(fs.readFileSync(path, 'utf-8')) as T;
}

const users = loadJson<{ username: string; password: string }[]>('test-data/users.json');

See the full approach in Read JSON data in Playwright.


✅ Best Practices

  • Use generics when the same logic works for different types; do not add <T> when one type is enough.
  • Let TypeScript infer T whenever possible; pass it explicitly when inference cannot know it (for example API responses).
  • Add constraints (extends) so the function only accepts types it can really handle.
  • Prefer generics over any. any switches off type checking; generics keep it on.
  • Remember that as T is a promise you make to the compiler; validate important API responses with assertions.

🏋️ Practice Exercises

  1. Write a generic function lastItem<T>(arr: T[]): T | undefined.
  2. Write toMap<T, K extends keyof T>(items: T[], key: K) that returns a Map keyed by that property.
  3. Create interface Result<T> { ok: boolean; value?: T; error?: string } and a function that returns it.
  4. Build a generic Queue<T> class with enqueue, dequeue and size.

❓ FAQ

🤔 What are generics in TypeScript in simple terms?

A way to write a function, interface or class once and use it with any type, while TypeScript still tracks exactly which type is used each time.

🤔 What does <T> mean in TypeScript?

T is a type parameter: a placeholder name for a type that will be provided (or inferred) when the code is used.

🤔 What is the difference between generics and any?

any turns off type checking. Generics keep type checking: if you pass strings in, TypeScript knows you get strings out.

🤔 What does T extends mean in generics?

It is a constraint. T extends { id: number } means T can be any type, as long as it has a numeric id property.

🤔 Where are generics used in Playwright?

In Promise<T> return types, test.extend<Fixtures>() for custom fixtures, and typed helpers such as a getJson<T>() API function.


🎯 Next Steps

🎬 Watch the full TypeScript tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

✎ Practise what you learned: 30 TypeScript generics programs with solutions →

TypeScript Classes for Beginners: Constructors, Inheritance, Access Modifiers and Page Objects

Classes are the heart of object-oriented programming and the reason Playwright frameworks stay clean as they grow. This beginner guide explains TypeScript classes in plain language, from your first constructor to a working Page Object Model.

📖 What You’ll Learn: class syntax, constructors, parameter properties, public/private/protected/readonly, inheritance with extends and super, getters and setters, static members, abstract classes, implementing interfaces, and Page Object Model classes in Playwright.


🏗️ What Is a Class?

A class is a template for creating objects. It bundles data (properties) and behavior (methods) together. Each object created from a class is called an instance.

A simple analogy: a class is the architect’s plan for a house, and each house built from that plan is an object. Every house has the same rooms (properties) and the same doors and switches (methods), but each one can have different paint and furniture (values).

In Playwright, classes are the foundation of the Page Object Model: each page of your application becomes a class with locators as properties and user actions as methods.


✍️ Creating Your First Class

class Car {
  brand: string;
  speed: number;

  constructor(brand: string, speed: number) {
    this.brand = brand;
    this.speed = speed;
  }

  describe(): string {
    return this.brand + ' runs at ' + this.speed + ' km/h';
  }
}

const car1 = new Car('Tata', 120);   // create an instance (object)
const car2 = new Car('Honda', 140);

console.log(car1.describe()); // Tata runs at 120 km/h
console.log(car2.brand);      // Honda

Key words to remember:

  • class declares the template.
  • constructor runs once when you call new and sets up the starting values.
  • this refers to the current object.
  • new creates a fresh object from the class.

⚠️ Common mistake: Forgetting this. inside a method is the most common beginner error. Write this.speed, not speed, to read the object’s own property.


⚡ Parameter Properties: The Short Way

TypeScript lets you declare and assign properties directly in the constructor by adding an access modifier (public, private, protected or readonly) before the parameter. You will see this in almost every Playwright page object.

// Long form
class UserLong {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}

// Short form: same result, less code
class User {
  constructor(public name: string, private password: string) {}
}

const u = new User('admin', 'secret');
console.log(u.name);       // admin
// console.log(u.password); // ❌ Error: 'password' is private

🔐 Access Modifiers: public, private, protected, readonly

Access modifiers control who can use a property or method.

ModifierAccessible fromTypical use
public (default)AnywhereMethods tests call, like login()
privateOnly inside the same classInternal helpers and secrets
protectedThe class and its child classesShared helpers in a base page
readonlyRead anywhere, set only in the constructorLocators, URLs
class BankAccount {
  readonly accountNumber: string;
  private balance = 0;

  constructor(accountNumber: string) {
    this.accountNumber = accountNumber;
  }

  deposit(amount: number): void {
    if (amount <= 0) throw new Error('Amount must be positive');
    this.balance += amount;
  }

  getBalance(): number {
    return this.balance;
  }
}

const acc = new BankAccount('SB-1001');
acc.deposit(500);
console.log(acc.getBalance()); // 500
// acc.balance = 1000000;      // ❌ Error: private

🧬 Inheritance with extends and super

Inheritance lets one class reuse another class. The child class gets every property and method of the parent and can add or override its own. Call super() in the child constructor to run the parent constructor first.

class Employee {
  constructor(public name: string, protected salary: number) {}

  getDetails(): string {
    return this.name + ' earns ' + this.salary;
  }
}

class Manager extends Employee {
  constructor(name: string, salary: number, public teamSize: number) {
    super(name, salary); // must come first
  }

  // Override the parent method
  getDetails(): string {
    return super.getDetails() + ' and manages ' + this.teamSize + ' people';
  }
}

const m = new Manager('Neha', 150000, 8);
console.log(m.getDetails()); // Neha earns 150000 and manages 8 people

🧰 Getters, Setters and Static Members

Getters and setters look like properties but run code. Static members belong to the class itself, not to each object. They are handy for shared constants and utility methods.

class Temperature {
  private celsius = 0;

  get fahrenheit(): number {
    return this.celsius * 9 / 5 + 32;
  }

  set value(c: number) {
    if (c < -273.15) throw new Error('Below absolute zero');
    this.celsius = c;
  }
}

const t = new Temperature();
t.value = 25;
console.log(t.fahrenheit); // 77

class TestUtils {
  static readonly DEFAULT_TIMEOUT = 30000;

  static randomEmail(): string {
    return 'user' + Date.now() + '@test.com';
  }
}

console.log(TestUtils.DEFAULT_TIMEOUT); // no "new" needed
console.log(TestUtils.randomEmail());

🧱 Abstract Classes

An abstract class cannot be created directly with new. It is a base for other classes and can force them to implement certain methods. This is useful for a BasePage that every page must extend.

abstract class Shape {
  abstract area(): number; // child classes MUST implement this

  describe(): string {
    return 'Area is ' + this.area().toFixed(2);
  }
}

class Circle extends Shape {
  constructor(private radius: number) { super(); }
  area(): number { return Math.PI * this.radius ** 2; }
}

console.log(new Circle(2).describe()); // Area is 12.57
// new Shape(); // ❌ Error: cannot create an instance of an abstract class

🤝 Classes and Interfaces Together

A class can implement an interface. The interface describes *what* must exist and the class provides *how* it works. If the class misses a member, TypeScript reports an error.

interface Reporter {
  report(testName: string, passed: boolean): void;
}

class ConsoleReporter implements Reporter {
  report(testName: string, passed: boolean): void {
    console.log((passed ? '✅ ' : '❌ ') + testName);
  }
}

Classes vs interfaces in one line: an interface is a compile-time contract with no code, while a class is real code that creates objects at runtime.


🎭 Classes in Playwright: Page Object Model

Here is a small but realistic Page Object Model built with everything you learned: readonly locators, a constructor, a protected base helper, inheritance and public action methods.

1. Base page

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

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

  abstract readonly path: string;

  async open(): Promise<void> {
    await this.page.goto('https://www.saucedemo.com' + this.path);
  }
}

2. Login page

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

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

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

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

3. The test stays short and readable

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

test('valid user can log in', async ({ page }) => {
  const loginPage = new LoginPage(page);
  await loginPage.open();
  await loginPage.login('standard_user', 'secret_sauce');
  await expect(page).toHaveURL(/inventory/);
});

test('locked user sees an error', async ({ page }) => {
  const loginPage = new LoginPage(page);
  await loginPage.open();
  await loginPage.login('locked_out_user', 'secret_sauce');
  await expect(loginPage.error).toContainText('locked out');
});

Go deeper with Playwright Page Object Model step by step and Playwright Custom Fixtures, which can create page objects for you automatically.


✅ Best Practices

  • One class per page or component; keep each class focused on one responsibility (see SOLID principles with Playwright).
  • Mark locators readonly so they cannot be reassigned by accident.
  • Keep assertions in tests, and keep actions in page classes.
  • Use private for helpers the tests should not call directly.
  • Prefer composition (a page that *has* a header component) over deep inheritance chains.

❓ FAQ

🤔 What is the difference between a class and an object in TypeScript?

A class is the template; an object is a real value created from it with new. One class can create many objects.

🤔 What is a constructor in TypeScript?

A special method named constructor that runs automatically when you create an object with new. It sets the starting values of properties.

🤔 When should I use a class instead of an interface?

Use a class when you need real behavior and to create objects at runtime, such as page objects. Use an interface when you only need to describe a shape or contract.

🤔 Why do Playwright page objects use classes?

Classes group a page’s locators and actions in one place, so tests read like user steps and a UI change only needs one fix in the page class.

🤔 What does super() do?

In a child class constructor, super() calls the parent class constructor. It must run before you use this.


🎯 Next Steps

🎬 Watch the full TypeScript tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

✎ Practise what you learned: 30 TypeScript class programs with solutions →

TypeScript Interfaces Explained: Examples, Interface vs Type, and Playwright Use Cases

Interfaces are how TypeScript describes the shape of your data. In test automation they keep test data, API responses and page objects consistent, so typos are caught in the editor instead of in a failed CI run. This guide explains interfaces from scratch with simple examples.

📖 What You’ll Learn: interface syntax, optional and readonly properties, default values, methods in interfaces, extends, index signatures, interface vs type, interface vs class, and how to use interfaces in Playwright tests.


📐 What Is an Interface in TypeScript?

An interface is a named description of what an object must look like: which properties it has, what type each one is, and which methods it provides. Think of it as a contract or a blueprint. Any object that claims to follow the interface must match it, or TypeScript shows an error before your code runs.

Interfaces do not exist at runtime. They are removed when TypeScript compiles to JavaScript, so they add safety without adding any code to your tests.

interface User {
  username: string;
  password: string;
  age: number;
}

const tester: User = {
  username: 'standard_user',
  password: 'secret_sauce',
  age: 28,
};

// ❌ Error: Property 'age' is missing in type
// const broken: User = { username: 'x', password: 'y' };

💡 Tip: By convention, interface names use PascalCase (User, LoginPage, ApiResponse). Do not add an I prefix like IUser; the TypeScript team recommends against it.


🧩 Interface Example: Optional and Readonly Properties

Just like object types, interface properties can be optional (?) or readonly.

interface TestEnvironment {
  readonly name: string;    // cannot change after creation
  baseUrl: string;
  apiKey?: string;          // optional
  timeout?: number;         // optional
}

const qa: TestEnvironment = { name: 'QA', baseUrl: 'https://qa.sqatools.in' };

qa.baseUrl = 'https://qa2.sqatools.in'; // ✅
// qa.name = 'PROD';                    // ❌ read-only

🎚️ Default Values for Interface Properties

A common beginner question is “how do I give an interface a default value?”. Interfaces only describe types, so they cannot hold values. Instead, set defaults where the object is created, usually with the spread operator or default parameters.

interface BrowserOptions {
  browser: 'chromium' | 'firefox' | 'webkit';
  headless?: boolean;
  slowMo?: number;
}

const defaultOptions: Required<BrowserOptions> = {
  browser: 'chromium',
  headless: true,
  slowMo: 0,
};

function createOptions(custom: Partial<BrowserOptions> = {}): Required<BrowserOptions> {
  return { ...defaultOptions, ...custom };
}

createOptions({ headless: false });
// { browser: 'chromium', headless: false, slowMo: 0 }

📝 Note: Partial<T> makes every property optional and Required<T> makes every property required. They are built-in utility types that work with any interface.


🛠️ Methods and Functions in Interfaces

Interfaces can describe methods too. This is exactly how you describe what a page object must be able to do.

interface LoginActions {
  open(): Promise<void>;
  login(username: string, password: string): Promise<void>;
  getErrorMessage(): Promise<string>;
}

// An interface can also describe a standalone function type
interface Formatter {
  (value: number): string;
}

const toPrice: Formatter = (value) => '₹' + value.toFixed(2);
console.log(toPrice(499)); // ₹499.00

🔗 Extending Interfaces

Interfaces can extend other interfaces to reuse properties. The new interface gets everything from the parent plus its own properties. You can extend more than one interface at once.

interface Person {
  firstName: string;
  lastName: string;
}

interface Employee extends Person {
  employeeId: number;
  department: string;
}

interface Timestamps {
  createdAt: Date;
}

interface Admin extends Employee, Timestamps {
  permissions: string[];
}

const lead: Admin = {
  firstName: 'Ravi',
  lastName: 'Kumar',
  employeeId: 101,
  department: 'QA',
  createdAt: new Date(),
  permissions: ['create-user', 'delete-user'],
};

📚 Interfaces for Arrays, Nested Data and Dynamic Keys

interface Address { city: string; zip: string }

interface Customer {
  id: number;
  name: string;
  address: Address;          // nested interface
  tags: string[];            // array of strings
  orders: { id: number; total: number }[]; // array of objects
}

// Index signature: any number of string keys
interface Headers {
  [header: string]: string;
}

const headers: Headers = { 'Content-Type': 'application/json', Accept: '*/*' };

⚔️ Interface vs Type: What Is the Difference?

This is one of the most searched TypeScript questions. For describing objects, both work and look almost the same. The differences:

Featureinterfacetype
Describe object shapes✅ Yes✅ Yes
Extend / reuseextends keywordIntersection &
Union types ('a' | 'b')❌ No✅ Yes
Primitives and tuples❌ No✅ Yes
Declaration merging (same name twice)✅ Merges❌ Error
Implemented by classes✅ Yes✅ Yes (object types)
// Same shape, two ways
interface UserA { name: string }
type UserB = { name: string };

// Extending
interface AdminA extends UserA { role: string }
type AdminB = UserB & { role: string };

// Only a type can do this
type Browser = 'chromium' | 'firefox' | 'webkit';
type Point = [number, number];

// Only an interface can do this (declaration merging)
interface Settings { theme: string }
interface Settings { language: string }
const s: Settings = { theme: 'dark', language: 'en' };

💡 Tip: A simple rule for beginners: use interface for objects and class contracts (page objects, API models), and use type for unions, tuples and combinations. Be consistent within your project.


🏛️ Interface vs Class

An interface only describes shape and is removed at compile time. A class creates real objects at runtime and can contain code, constructors and default values. A class can implement an interface to promise it follows that contract.

interface Logger {
  log(message: string): void;
}

class ConsoleLogger implements Logger {
  log(message: string): void {
    console.log('[test] ' + message);
  }
}

// ❌ Error if the class forgets the log() method

🎭 Interfaces in Playwright: Real Examples

1. Typing test data

// test-data/users.ts
export interface UserData {
  username: string;
  password: string;
  expectedPage: string;
}

export const users: Record<'standard' | 'problem', UserData> = {
  standard: { username: 'standard_user', password: 'secret_sauce', expectedPage: '/inventory.html' },
  problem:  { username: 'problem_user',  password: 'secret_sauce', expectedPage: '/inventory.html' },
};

2. Typing an API response

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

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

test('GET a post returns the correct shape', async ({ request }) => {
  const response = await request.get('https://jsonplaceholder.typicode.com/posts/1');
  expect(response.ok()).toBeTruthy();

  const post: Post = await response.json();
  expect(post.id).toBe(1);
  expect(typeof post.title).toBe('string'); // editor autocompletes post.title
});

3. A contract for page objects

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

interface BasePage {
  readonly page: Page;
  readonly url: string;
  open(): Promise<void>;
}

export class LoginPage implements BasePage {
  readonly url = 'https://www.saucedemo.com/';
  constructor(readonly page: Page) {}

  async open() {
    await this.page.goto(this.url);
  }

  async login(user: { username: string; password: string }) {
    await this.page.getByPlaceholder('Username').fill(user.username);
    await this.page.getByPlaceholder('Password').fill(user.password);
    await this.page.getByRole('button', { name: 'Login' }).click();
  }
}

Read the full pattern in Playwright Page Object Model step by step.


✅ Best Practices

  • Name interfaces after what they represent: UserData, ApiResponse, CheckoutPage.
  • Keep shared interfaces in one folder (for example types/) and export them.
  • Use extends to build specific interfaces from general ones instead of copy-pasting properties.
  • Type every API response you assert on. Autocomplete then prevents typos in property names.
  • Prefer Partial<T> for “update” or “override” objects instead of making every property optional.

❓ FAQ

🤔 What is an interface in TypeScript in simple words?

It is a named blueprint that lists the properties and methods an object must have. TypeScript checks every object against it while you write code.

🤔 Should I use interface or type in TypeScript?

Both work for objects. Use interface for object shapes and class contracts, and type for unions, tuples and other combinations. Pick one style per project and stay consistent.

🤔 Can a TypeScript interface have default values?

No. Interfaces only describe types. Set defaults when creating the object, for example const opts = { ...defaults, ...custom }.

🤔 Can an interface extend multiple interfaces?

Yes: interface Admin extends Employee, Timestamps {} combines all properties from both parents.

🤔 Do interfaces slow down my tests?

No. Interfaces are removed during compilation and produce zero JavaScript, so they have no runtime cost.


🎯 Next Steps

🎬 Watch the full TypeScript tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

✎ Practise what you learned: 30 TypeScript interface programs with solutions →