Configure Playwright Python Tests: pytest.ini, pyproject.toml and conftest.py

Playwright with TypeScript has a single playwright.config.ts file. In Python, configuration is split between two places that every pytest user knows: a settings file (pytest.ini or pyproject.toml) for default command-line options, and conftest.py for Python code that customises the browser, context and timeouts. In this lesson you will build a complete, realistic configuration step by step and verify each setting with a test.

📖 What You’ll Learn: where pytest looks for configuration, addopts, testpaths and base_url in pytest.ini and pyproject.toml, how addopts combines with command-line options, overriding browser_context_args and browser_type_launch_args in conftest.py, per-test context settings with a marker, and setting default timeouts for actions and assertions.


🗺️ Where Configuration Lives

What you want to configureWhere it goesExample
Default command-line optionspytest.ini or pyproject.toml (addopts)--browser chromium --tracing retain-on-failure
Where tests live, base URLpytest.ini or pyproject.tomltestpaths = tests, base_url = https://...
Browser launch settingsconftest.py fixture browser_type_launch_argsextra Chromium flags
Context settings (viewport, locale, timezone, HTTPS errors)conftest.py fixture browser_context_args{"viewport": {"width": 1440, "height": 900}}
Timeoutsconftest.pyexpect.set_options(timeout=10_000)

pytest finds its settings file by looking in the folder you run it from and then in parent folders. Put the settings file and conftest.py in your project’s root folder, next to the tests folder.


📄 Option 1: pytest.ini

Create pytest.ini in the project root:

📄 pytest.ini

[pytest]
# Look for tests only in the tests folder
testpaths = tests

# Options added to every pytest run
addopts = -v --tracing retain-on-failure --screenshot only-on-failure

# Relative URLs in page.goto() are resolved against this
base_url = https://sqatools.in
  • [pytest] is the required section header.
  • testpaths = tests makes a bare pytest command search only the tests folder, which is faster and avoids collecting stray files.
  • addopts is added in front of whatever you type, so every run now uses verbose output and keeps traces and screenshots of failures.
  • base_url lets tests call page.goto("/automation-practice-page/"). A --base-url on the command line takes priority over this value.
  • Lines starting with # are comments.

📄 Option 2: pyproject.toml

Many Python projects keep all tool settings in pyproject.toml. The same configuration looks like this:

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-v --tracing retain-on-failure --screenshot only-on-failure"
base_url = "https://sqatools.in"
  • The section is [tool.pytest.ini_options], and values follow TOML rules: strings in quotes, lists in square brackets.
  • pytest 9 also accepts a native [tool.pytest] table, where addopts is a list: addopts = ["-v", "--tracing", "retain-on-failure"]. The ini_options form works on every pytest version, so it is the safer choice for shared projects.

⚠️ Watch out: Use only one settings file. If both pytest.ini and a [tool.pytest.ini_options] section exist, pytest.ini wins and the pyproject settings are ignored. The only sign is a short note in the run header: configfile: pytest.ini (WARNING: ignoring pytest config in pyproject.toml!). Check the configfile: line whenever settings seem to have no effect.


⚖️ How addopts Combines with the Command Line

addopts does not replace what you type; it is added before it. For options that take one value, the last one wins, so the command line overrides the file. But --browser can be repeated, so the values add up. To see it, imagine addopts = --browser firefox in pytest.ini and this small test:

def test_which_browser(page, browser_name):
    print("RUN", browser_name)

⌨️ Terminal

pytest -q -s --browser webkit

🖥️ Output

RUN firefox
RUN webkit
2 passed in 2.04s

The test ran in both Firefox (from the file) and WebKit (from the command line). If you want to switch browsers freely from the command line, do not put --browser in addopts; Chromium is already the default.


🐍 conftest.py: Python-Powered Configuration

conftest.py is a special pytest file. Fixtures defined in it are available to every test in its folder and sub-folders without importing anything. pytest-playwright builds its browser, context and page fixtures from a few settings fixtures, and you customise them by redefining those settings fixtures in conftest.py.

Create conftest.py in the project root:

📄 conftest.py

import pytest
from playwright.sync_api import Page, expect


@pytest.fixture(scope="session")
def browser_context_args(browser_context_args):
    """Settings applied to every new browser context (and so every page)."""
    return {
        **browser_context_args,                        # keep the plugin's own settings
        "viewport": {"width": 1440, "height": 900},    # larger desktop window
        "locale": "en-GB",                             # browser language
        "timezone_id": "Europe/London",                # browser time zone
        "ignore_https_errors": True,                   # accept self-signed test certificates
    }


@pytest.fixture(scope="session")
def browser_type_launch_args(browser_type_launch_args):
    """Settings used when the browser process is launched."""
    return {
        **browser_type_launch_args,
        "slow_mo": 0,                                  # keep 0 in CI; raise it to watch tests
    }


@pytest.fixture(autouse=True)
def default_timeouts(page: Page):
    """Runs before every test: make actions and navigations time out after 15 s."""
    page.set_default_timeout(15_000)
    page.set_default_navigation_timeout(30_000)


# Web-first assertions (expect) wait 5 s by default; give slow pages 10 s
expect.set_options(timeout=10_000)

Line by line:

  1. **browser_context_args** is a session-scoped fixture provided by pytest-playwright. Your version receives the original as a parameter (also named browser_context_args), and returns a new dictionary that starts with **browser_context_args so the plugin’s own settings (such as the --base-url and --device values) are kept, then adds yours.
  2. The keys are the same as the parameters of browser.new_context(): viewport, locale, timezone_id, ignore_https_errors, user_agent, color_scheme, geolocation, permissions, storage_state, and more.
  3. **scope="session"** must match the plugin’s fixture, because the settings are calculated once for the whole run.
  4. **browser_type_launch_args** works the same way for launch() options such as slow_mo, args (extra browser command-line flags) or downloads_path.
  5. **autouse=True** runs the default_timeouts fixture for every test automatically. It asks for page, so it changes the timeouts of the very page your test receives.
  6. **expect.set_options(timeout=10_000)** changes the default wait for every expect() assertion. Because conftest.py is imported before the tests run, it applies everywhere.

💡 Tip: 15_000 is the same number as 15000. Python ignores the underscores; they just make large numbers easier to read.


✅ Prove the Configuration Works

Create tests/test_config.py:

📄 tests/test_config.py

from playwright.sync_api import Page, expect


def test_context_settings_are_applied(page: Page):
    page.goto("/automation-practice-page/")    # relative URL thanks to base_url

    assert page.viewport_size == {"width": 1440, "height": 900}
    assert page.evaluate("navigator.language") == "en-GB"
    assert page.evaluate("Intl.DateTimeFormat().resolvedOptions().timeZone") == "Europe/London"


def test_base_url_is_used(page: Page):
    page.goto("/automation-practice-page/")
    expect(page).to_have_url("https://sqatools.in/automation-practice-page/")

Run pytest with no arguments:

⌨️ Terminal

pytest

🖥️ Output

configfile: pytest.ini
testpaths: tests
plugins: playwright-0.10.0
collecting ... collected 3 items

tests/test_config.py::test_context_settings_are_applied[chromium] PASSED [ 33%]
tests/test_config.py::test_base_url_is_used[chromium] PASSED             [ 66%]
tests/test_markers.py::test_dark_mode_for_one_test[chromium] PASSED      [100%]
  • configfile: pytest.ini and testpaths: tests confirm which settings file pytest used.
  • The -v style output appears without typing -v, because it is in addopts.
  • The plugins line on your machine may list different plugins; that is fine.

The same tests also pass in Firefox, which shows the settings are browser-independent:

⌨️ Terminal

pytest --browser firefox

🎯 Different Settings for One Test

Sometimes one test needs something special, such as dark mode or a different language. pytest-playwright provides a marker for that. Create tests/test_markers.py:

📄 tests/test_markers.py

import pytest
from playwright.sync_api import Page


@pytest.mark.browser_context_args(color_scheme="dark", locale="fr-FR")
def test_dark_mode_for_one_test(page: Page):
    page.goto("/automation-practice-page/")

    assert page.evaluate("matchMedia('(prefers-color-scheme: dark)').matches") is True
    assert page.evaluate("navigator.language") == "fr-FR"
  • @pytest.mark.browser_context_args(...) adds or overrides context settings for this test only.
  • Settings from conftest.py that the marker does not mention (here the 1440×900 viewport) still apply.
  • matchMedia(...) is a browser API; the test asks the page whether it is in dark mode.

🗂️ The Project Structure

🖥️ Output

playwright-python-demo/
├── .venv/
├── conftest.py          # fixtures: context args, launch args, timeouts
├── pytest.ini           # defaults: testpaths, addopts, base_url
├── requirements.txt
└── tests/
    ├── test_config.py
    └── test_markers.py

🔁 TypeScript Config vs Python Config

If you know Playwright with TypeScript, this table maps the familiar playwright.config.ts settings to Python:

playwright.config.tsPython equivalent
testDir: './tests'testpaths = tests
use: { baseURL }base_url in pytest.ini, or --base-url
use: { viewport, locale, timezoneId }browser_context_args fixture in conftest.py
use: { trace: 'retain-on-failure' }--tracing retain-on-failure in addopts
expect: { timeout: 10000 }expect.set_options(timeout=10_000)
use: { actionTimeout }page.set_default_timeout() in an autouse fixture
projects: [...]--browser (repeatable) or --device
retries: 2pytest-rerunfailures plugin: --reruns 2
workers: 4pytest-xdist plugin: -n 4

❓ Frequently Asked Questions

🤔 Can I have more than one conftest.py?

Yes. A conftest.py in a sub-folder adds or overrides fixtures for the tests in that folder only. The root conftest.py applies to everything. You will use this in Sharing Fixtures with conftest.py.

🤔 Why does my browser_context_args override seem to do nothing?

The most common causes are a missing scope="session", forgetting to return the dictionary, or a key misspelled (for example timezone instead of timezone_id). Run a test that prints page.viewport_size or navigator.language to confirm.

🤔 Where do I set the browser headless mode in config?

Headless is the default. Add --headed to addopts if you want windows on your own machine, but do not commit that, because CI servers have no screen.

🤔 Should I put secrets like passwords in pytest.ini?

No. Keep secrets in environment variables or a .env file that is not committed. You will learn this in Environment Variables and .env Files.


🏁 Summary

  • pytest.ini or pyproject.toml holds testpaths, addopts and base_url; use only one settings file.
  • addopts is added before command-line options, and repeatable options like --browser add up.
  • Override browser_context_args and browser_type_launch_args in conftest.py (session scope, keep the original with **).
  • Use an autouse fixture for action timeouts, expect.set_options() for assertion timeouts, and the browser_context_args marker for one-off settings.

Next, you will let Playwright write tests for you with Codegen, and learn how to turn recorded code into clean pytest tests.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

Run Playwright Python Tests: pytest and pytest-playwright CLI Options Explained

You can change how your whole test suite runs without touching a single line of test code. pytest-playwright adds options to the pytest command for picking browsers, watching tests run, emulating phones and capturing screenshots, videos and traces when something fails. In this lesson you will try each option on a small test file and see exactly what it produces.

📖 What You’ll Learn: running tests in Chromium, Firefox and WebKit, using installed Chrome or Edge, headed mode and slow motion, device emulation, capturing screenshots, videos and traces only on failure, the test-results folder, –base-url, and the core pytest flags for selecting and reporting tests.


🧪 The Test File for This Lesson

Create tests/test_cli.py. It has one passing test, one test that fails on purpose (so you can see failure artifacts), one test that prints the viewport size, and one test that uses a relative URL:

📄 tests/test_cli.py

from playwright.sync_api import Page, expect


def test_practice_title(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    expect(page).to_have_title("Automation Practice Page - SQA Tools")


def test_broken_heading(page: Page):
    # Fails on purpose: the real heading text is "Text Fields"
    page.goto("https://sqatools.in/automation-practice-page/")
    heading = page.get_by_role("heading", name="Text Fields")
    expect(heading).to_have_text("Text Boxes", timeout=1000)


def test_viewport(page: Page, browser_name: str):
    size = page.viewport_size
    is_mobile = "Mobile" in page.evaluate("navigator.userAgent")
    print(f"\n{browser_name}: viewport {size['width']}x{size['height']}, mobile user agent: {is_mobile}")


def test_relative_url(page: Page):
    # Works only when a base URL is set (see --base-url below)
    page.goto("/automation-practice-page/")
    expect(page).to_have_url("https://sqatools.in/automation-practice-page/")
  • browser_name is another pytest-playwright fixture: a string such as "chromium". Asking for it is as simple as adding a parameter.
  • page.viewport_size returns a dictionary like {'width': 1280, 'height': 720}.
  • timeout=1000 makes the failing assertion give up after 1 second instead of the default 5, so the demo is quick.

🌐 Choose the Browser: –browser and –browser-channel

Without options, tests run in Chromium. Pick another engine with --browser:

⌨️ Terminal

pytest --browser firefox
pytest --browser webkit

Repeat the option to run every test in several browsers in one go:

⌨️ Terminal

pytest --browser chromium --browser firefox --browser webkit -k title

🖥️ Output

...                                                                      [100%]
3 passed, 9 deselected in 9.37s

The single test_practice_title test ran three times, once per browser (that is what the three dots mean). With -v you would see the suffixes [chromium], [firefox] and [webkit].

To run Google Chrome or Microsoft Edge as installed on your machine (instead of Playwright’s own Chromium build), use a channel:

⌨️ Terminal

pytest --browser-channel chrome
pytest --browser-channel msedge

💡 Tip: Testing in branded Chrome or Edge is useful when you must match exactly what your users run. For everyday runs, Playwright’s bundled Chromium is faster to set up and identical across machines.


👀 Watch Tests Run: –headed and –slowmo

⌨️ Terminal

pytest --headed
pytest --headed --slowmo 1000
  • --headed opens visible browser windows. By default tests are headless.
  • --slowmo 1000 waits 1000 milliseconds after every Playwright action, so you can follow each step. Never leave it on in CI: it makes every test much slower.

📱 Emulate a Device: –device

--device applies one of Playwright’s built-in device profiles (screen size, user agent, touch support, pixel ratio) to every test:

⌨️ Terminal

pytest -s --device "iPhone 13" -k viewport

🖥️ Output

chromium: viewport 390x664, mobile user agent: True
1 passed, 3 deselected in 0.49s

Without the option, the same test prints the default desktop viewport:

⌨️ Terminal

pytest -s -k viewport

🖥️ Output

chromium: viewport 1280x720, mobile user agent: False
  • Device names must match Playwright’s list exactly, including capitals and spaces, so put them in quotes. Popular ones include "iPhone 13", "Pixel 7" and "iPad Pro 11".
  • The browser engine is still chosen by --browser (Chromium by default). For the most realistic iPhone emulation, combine --browser webkit --device "iPhone 13".
  • -s turns off pytest’s output capturing so that print() output appears in the terminal.

You will go deeper in Mobile Device Emulation.


📸 Capture Evidence: –screenshot, –video and –tracing

When a test fails in CI, you need evidence. These options record it automatically:

OptionValuesWhat you get
--screenshoton, off, only-on-failureA PNG taken at the end of each test
--full-page-screenshotflagMake those screenshots capture the full scrolling page (use with --screenshot)
--videoon, off, retain-on-failureA .webm recording of each test
--tracingon, off, retain-on-failureA trace.zip you can replay step by step in the Trace Viewer
--outputfolder pathWhere all of these go (default test-results)

The most useful combination keeps evidence only for failed tests:

⌨️ Terminal

pytest -k "not relative" --screenshot only-on-failure --video retain-on-failure --tracing retain-on-failure

🖥️ Output

FAILED tests/test_cli.py::test_broken_heading[chromium] - AssertionError: Loc...
1 failed, 2 passed, 1 deselected in 6.12s

(-k "not relative" skips the relative-URL test for now, because it needs the --base-url option shown later in this lesson.)

The test-results folder now holds one sub-folder, for the failed test only:

🖥️ Output

test-results/
└── tests-test-cli-py-test-broken-heading-chromium/
    ├── test-failed-1.png
    ├── trace.zip
    └── video.webm
  • The folder name is built from the file name, the test name and the browser, so failures in different browsers never overwrite each other.
  • Passing tests left nothing behind, which keeps CI artifacts small.
  • Open the trace with playwright show-trace test-results/tests-test-cli-py-test-broken-heading-chromium/trace.zip. You will learn the Trace Viewer in Module 11.

📝 Note: pytest-playwright clears the output folder at the start of each run, so old artifacts never get mixed with new ones.


🔗 Shorter URLs: –base-url

Typing the full URL in every test is repetitive, and it makes it hard to run the same tests against a staging server. Set a base URL once and use relative paths:

⌨️ Terminal

pytest --base-url https://sqatools.in -k relative

🖥️ Output

.                                                                        [100%]
1 passed, 3 deselected in 1.29s

page.goto("/automation-practice-page/") was resolved against the base URL. In pytest-playwright 0.10 the --base-url option works out of the box. You can also set it with the PYTEST_BASE_URL environment variable or a base_url entry in pytest.ini, which you will do in the next lesson.


🎯 Core pytest Options You Will Use Every Day

These come from pytest itself and combine freely with the Playwright options:

OptionMeaning
-v / -qMore / less output
-k "expression"Run tests whose names match, e.g. -k "login and not locked"
-m markerRun tests with a marker, e.g. -m smoke (Module 3)
-xStop after the first failure
--maxfail=3Stop after three failures
-sShow print() output
--lfRe-run only the tests that failed last time
--collect-onlyList the tests without running them
--durations=5Show the five slowest tests

For example, --collect-only -q lists every test with its browser suffix:

⌨️ Terminal

pytest --collect-only -q

🖥️ Output

tests/test_cli.py::test_practice_title[chromium]
tests/test_cli.py::test_broken_heading[chromium]
tests/test_cli.py::test_viewport[chromium]
tests/test_cli.py::test_relative_url[chromium]

4 tests collected in 0.00s

🧾 Quick Reference

⌨️ Terminal

# All browsers, verbose
pytest --browser chromium --browser firefox --browser webkit -v

# Debug one test visually
pytest tests/test_login.py::test_valid_login_shows_products --headed --slowmo 500

# CI-style run with evidence on failure
pytest --tracing retain-on-failure --screenshot only-on-failure --video retain-on-failure

# Same tests against another environment
pytest --base-url https://staging.example.com

To see every option on your machine, run pytest --help and look for the Playwright section.


❓ Frequently Asked Questions

🤔 How do I avoid typing the same options every time?

Put them in the addopts setting of pytest.ini or pyproject.toml. That is the first thing you will do in the next lesson.

🤔 Can I run tests in parallel?

Yes, with the pytest-xdist plugin (pytest -n auto). It is covered in Parallel Execution with pytest-xdist.

🤔 Do these options affect browsers I create myself?

No. They configure the browser, context and page fixtures from pytest-playwright. A browser you launch yourself with sync_playwright() inside a test is not affected.

🤔 Is there a –retries option?

Not in pytest-playwright. Retries come from the pytest-rerunfailures plugin (pytest --reruns 2), covered in Module 6.


🏁 Summary

  • --browser (repeatable) and --browser-channel choose where tests run; --headed and --slowmo let you watch.
  • --device emulates phones and tablets; -s shows printed output.
  • --screenshot only-on-failure --video retain-on-failure --tracing retain-on-failure keeps evidence for failed tests in test-results.
  • --base-url lets tests use relative URLs; pytest’s own flags (-k, -x, -v, --lf) select and report tests.

Next, you will move these options into configuration files and learn how conftest.py customises the browser and context for the whole suite.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

Write and Run Your First pytest Playwright Test in Python

Now you will write real tests. With pytest and the pytest-playwright plugin, you never launch or close a browser yourself: you ask for a page, use it, and pytest cleans up. In this lesson you will understand every line of a Playwright test, automate a login page, add negative tests, run them in different ways, and learn to read a failure message.

📖 What You’ll Learn: test anatomy (test function, page fixture, expect), pytest discovery rules, writing a login test with Arrange-Act-Assert, negative tests, why every test gets a fresh page, running tests from the CLI, and reading a failing test’s output.


🧱 Anatomy of a Playwright Test

Create a tests folder in your project and add tests/test_title.py:

📄 tests/test_title.py

from playwright.sync_api import Page, expect                      # 1. imports


def test_practice_page_has_title(page: Page):                    # 2. a test function
    page.goto("https://sqatools.in/automation-practice-page/")   # 3. an action
    expect(page).to_have_title("Automation Practice Page - SQA Tools")   # 4. an assertion
  1. Imports. Page is the type of the page object (used for editor auto-complete) and expect creates Playwright assertions.
  2. A test function. pytest runs any function whose name starts with test_. The parameter page is a fixture: pytest-playwright sees the name, creates a fresh page in a new browser context, passes it in, and closes it after the test. The : Page part is a type hint; it does not change behaviour, but it gives you auto-complete in VS Code.
  3. An action. page.goto() opens the URL.
  4. An assertion. expect(page).to_have_title(...) checks the title. If it does not match yet, it retries for up to 5 seconds before failing. This is called a *web-first assertion*.

Run it:

⌨️ Terminal

pytest tests/test_title.py

🔍 How pytest Finds Your Tests

When you run pytest, it searches the current folder and its subfolders. By default it collects:

  • files named test_*.py or *_test.py,
  • functions named test_* in those files,
  • methods named test_* inside classes named Test* (the class must not have an __init__ method).

So tests/test_login.py with def test_valid_login(page) is found automatically, while tests/login.py or def check_login(page) would be silently ignored. You will learn how to change these rules in pytest Configuration.

⚠️ Watch out: A test file named test_something.py that is never collected is almost always caused by a typo in the file or function name. Run pytest --collect-only to list what pytest found without running it.


✍️ A Real Test: Login

Next, automate the login page of Sauce Demo (https://www.saucedemo.com), a free practice shop that accepts the username standard_user and password secret_sauce. Create tests/test_login.py:

📄 tests/test_login.py

import re

from playwright.sync_api import Page, expect


def test_valid_login_shows_products(page: Page):
    # Arrange: open the login page
    page.goto("https://www.saucedemo.com/")

    # Act: fill the form and submit
    page.get_by_placeholder("Username").fill("standard_user")
    page.get_by_placeholder("Password").fill("secret_sauce")
    page.get_by_role("button", name="Login").click()

    # Assert: we land on the products page
    expect(page).to_have_url(re.compile(r".*/inventory\.html"))
    expect(page.locator(".title")).to_have_text("Products")


def test_wrong_password_shows_error(page: Page):
    page.goto("https://www.saucedemo.com/")

    page.get_by_placeholder("Username").fill("standard_user")
    page.get_by_placeholder("Password").fill("wrong_password")
    page.get_by_role("button", name="Login").click()

    error = page.locator("[data-test='error']")
    expect(error).to_be_visible()
    expect(error).to_contain_text("Username and password do not match")


def test_locked_out_user_cannot_log_in(page: Page):
    page.goto("https://www.saucedemo.com/")

    page.get_by_placeholder("Username").fill("locked_out_user")
    page.get_by_placeholder("Password").fill("secret_sauce")
    page.get_by_role("button", name="Login").click()

    expect(page.locator("[data-test='error']")).to_contain_text("locked out")
    expect(page).to_have_url("https://www.saucedemo.com/")

What the new pieces do:

  • Arrange, Act, Assert. The comments split the first test into setting up, doing the user action, and checking the result. Keeping this shape makes tests easy to read and review.
  • get_by_placeholder("Username") finds an input by its placeholder text; get_by_role("button", name="Login") finds the button by its role and visible name, the way a user sees it.
  • to_have_url(re.compile(...)) accepts either an exact string or a regular expression. The pattern .*/inventory\.html means “any URL ending in /inventory.html”; the backslash makes the dot literal.
  • page.locator(".title") uses a CSS selector. to_have_text("Products") checks the element’s full text, while to_contain_text() checks for a substring.
  • "[data-test='error']" is a CSS attribute selector. Many apps add data-test or data-testid attributes for exactly this purpose.
  • The second and third tests are negative tests: they prove the app rejects bad input. A good suite always tests both the happy path and the failure paths.

Run the file with -v (verbose) to see each test by name:

⌨️ Terminal

pytest tests/test_login.py -v

🖥️ Output

tests/test_login.py::test_valid_login_shows_products[chromium] PASSED    [ 33%]
tests/test_login.py::test_wrong_password_shows_error[chromium] PASSED    [ 66%]
tests/test_login.py::test_locked_out_user_cannot_log_in[chromium] PASSED [100%]

The [chromium] suffix is added by pytest-playwright: it shows which browser ran the test. Chromium is the default, and you will run the same tests in Firefox and WebKit in the next lesson.


🔒 Every Test Gets a Fresh Page

The tests above never log out, yet the second test starts on the login page as a stranger. That is because each test receives a new browser context: new cookies, new storage, nothing left over from the previous test. This file proves it (tests/test_isolation.py):

📄 tests/test_isolation.py

from playwright.sync_api import Page


def test_first_saves_a_value(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    page.evaluate("localStorage.setItem('step', 'done')")
    assert page.evaluate("localStorage.getItem('step')") == "done"


def test_second_starts_clean(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    assert page.evaluate("localStorage.getItem('step')") is None
  • The first test stores a value in the page’s localStorage and checks it with a plain Python assert.
  • The second test opens the same site in its own fresh context and finds nothing there.

💡 Tip: Use plain assert for Python values you already have (numbers, strings, lists). Use expect(...) for anything on the page, because it waits and retries while the page catches up.


💥 Reading a Failure

Tests fail, and reading the failure quickly is a core skill. Here is a test with a deliberate mistake (tests/test_failing.py):

📄 tests/test_failing.py

from playwright.sync_api import Page, expect


def test_title_typo(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    expect(page).to_have_title("Automation Practise Page - SQA Tools")

The expected title says “Practise” instead of “Practice”. Run it:

⌨️ Terminal

pytest tests/test_failing.py

🖥️ Output

================================== FAILURES ===================================
__________________________ test_title_typo[chromium] __________________________

page = <Page url='https://sqatools.in/automation-practice-page/'>

    def test_title_typo(page: Page):
        page.goto("https://sqatools.in/automation-practice-page/")
>       expect(page).to_have_title("Automation Practise Page - SQA Tools")
E       AssertionError: Page title expected to be 'Automation Practise Page - SQA Tools'
E       Actual value: Automation Practice Page - SQA Tools
E       Call log:
E         - Expect "to_have_title" with timeout 5000ms
E           13 × locator resolved to <html lang="en-US" prefix="og: https://ogp.me/ns#">…</html>
E              - unexpected value "Automation Practice Page - SQA Tools"
E
E       Aria snapshot:
E       - link "Skip to content":
E         - /url: "#content"
E       - banner "Site":
E       ...  (the rest of the page structure, cut here)

tests\test_failing.py:6: AssertionError
=========================== short test summary info ===========================
FAILED tests/test_failing.py::test_title_typo[chromium] - AssertionError: Pag...
============================== 1 failed in 7.08s ==============================

How to read it, top to bottom:

  1. **The > marker** points at the line that failed, inside a copy of your test code.
  2. What was expected and what the page actually had (Actual value). Comparing these two lines usually reveals the bug immediately.
  3. The call log shows that Playwright kept checking for 5 seconds (the default assertion timeout) and saw the same wrong value each time, so this is not a timing problem.
  4. The aria snapshot (added by recent Playwright versions) is a text outline of the page at the moment of failure: headings, links, buttons, fields. It helps you see what was really on screen, especially in CI where you cannot watch the browser.
  5. The file and line number (test_failing.py:6) and the short summary list every failed test with its browser.

📝 Note: The exact retry count in the call log (here 13 ×) and the run time vary from run to run. That is normal.


▶️ Running Tests: The Essentials

CommandWhat it does
pytestRun every test pytest can find
pytest tests/test_login.pyRun one file
pytest tests/test_login.py::test_wrong_password_shows_errorRun one test
pytest -k "login and not locked"Run tests whose names match the expression
pytest -vShow each test name and result
pytest -xStop at the first failure
pytest --headedShow the browser window

The next lesson covers every Playwright-specific option, such as --browser, --slowmo, --screenshot and --tracing.


❓ Frequently Asked Questions

🤔 Why do I not need to launch or close the browser?

The page fixture from pytest-playwright does it. It reuses one browser for the whole run, creates a new context and page for each test, and closes them afterwards, even when the test fails.

🤔 Can I put tests in a class?

Yes. Name the class Test..., do not give it an __init__, and add page as a parameter to each method: def test_login(self, page: Page):. Classes are useful for grouping related tests.

🤔 Why use expect instead of assert?

expect waits and retries until the condition is true or the timeout (5 seconds by default) is reached. A plain assert page.title() == "..." checks only once, so it can fail if the page is still loading.

🤔 Why does the test name end with [chromium]?

pytest-playwright parametrizes tests by browser. If you run with --browser firefox --browser webkit, each test runs once per browser and the suffix shows which run you are looking at.


🏁 Summary

  • A test is a test_ function in a test_*.py file that asks for the page fixture.
  • expect() assertions wait and retry; use plain assert only for values you already hold.
  • Structure tests as Arrange, Act, Assert, and always include negative tests.
  • Each test gets a new context and page, so tests never share state.
  • Failures show expected vs actual values, a call log and the failing line.

Next, you will learn every pytest and pytest-playwright command-line option for running tests in different browsers, headed mode, slow motion and more.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

Your First Playwright Python Script with sync_playwright (Browser, Context and Page)

Before pytest takes over the browser for you, it is worth writing one complete Playwright script by hand. You will see exactly what happens when a test starts: Playwright launches a browser, creates an isolated context, opens a page, performs actions and closes everything down. Once you understand these four objects, every fixture and error message later in the course will make sense.

📖 What You’ll Learn: the Playwright object hierarchy (Playwright, Browser, BrowserContext, Page), launch options like headless and slow_mo, interacting with a real form, reading text and attributes, taking screenshots, proving that contexts are isolated, and closing resources safely with with and try/finally.


🧱 The Four Objects You Always Use

Every Playwright program, including every pytest test you will write, uses the same chain of objects:

ObjectCreated byWhat it represents
Playwrightsync_playwright()The running Playwright driver. Gives you chromium, firefox, webkit and devices.
Browserp.chromium.launch()One browser process (expensive to start, so reuse it).
BrowserContextbrowser.new_context()An isolated, incognito-like session with its own cookies, storage and cache. Cheap to create.
Pagecontext.new_page()One tab inside a context. Almost all actions happen here.

Think of the browser as a building, each context as a separate flat with its own key, and each page as a room in a flat. Two contexts never share cookies or logins, which is why Playwright tests do not leak state into each other.


✍️ A Complete First Script

This script opens the SQA Tools Automation Practice Page, fills in some fields, reads values back and saves a screenshot. Save it as first_script.py:

📄 first_script.py

from playwright.sync_api import sync_playwright


with sync_playwright() as p:
    # 1. Launch a browser and create an isolated context with one page
    browser = p.chromium.launch()
    context = browser.new_context()
    page = context.new_page()

    # 2. Open the practice page
    page.goto("https://sqatools.in/automation-practice-page/")
    print("Page title:", page.title())

    # 3. Type into text fields, located by their placeholder text
    page.get_by_placeholder("Enter username").fill("qa_learner")
    page.get_by_placeholder("Enter password").fill("Secret@123")

    # 4. Choose a radio button, tick a checkbox and pick a dropdown option
    page.get_by_role("radio", name="Female").check()
    page.get_by_role("checkbox", name="Python").check()
    page.locator("select").first.select_option("India")

    # 5. Read the values back from the page
    print("Username field:", page.get_by_placeholder("Enter username").input_value())
    print("Python checked:", page.get_by_role("checkbox", name="Python").is_checked())
    print("Second table row:", page.get_by_role("row").nth(2).inner_text())

    # 6. Save a screenshot of the visible part of the page
    page.screenshot(path="practice-page.png")

    # 7. Close everything
    context.close()
    browser.close()

Run it:

⌨️ Terminal

python first_script.py

🖥️ Output

Page title: Automation Practice Page - SQA Tools
Username field: qa_learner
Python checked: True
Second table row: 2	Rahul	Tester

A file named practice-page.png appears next to your script.

What each part does

  1. Launch and open. launch() starts the browser, new_context() creates a clean session, and new_page() opens a tab in it.
  2. **page.goto(url)** navigates and waits for the page’s load event before the next line runs.
  3. **get_by_placeholder("Enter username") creates a locator**: a description of how to find an element. Nothing is searched yet. fill() then finds the input, waits until it is editable, clears it and types the text.
  4. **get_by_role("radio", name="Female")** finds the element the way a screen reader would: by its role (radio) and accessible name (Female). check() ticks radios and checkboxes. select_option("India") picks the option whose value or label is India from the first <select> on the page.
  5. Reading values. input_value() returns what is typed in a field, is_checked() returns True or False, and inner_text() returns the visible text. nth(2) picks the third match (counting starts at 0, and row 0 is the header row). The cells in the printed row are separated by tab characters.
  6. **page.screenshot(path=...)** saves a PNG. Add full_page=True to capture the whole scrolling page.
  7. Closing. Closing the context closes its pages; closing the browser ends the process. Leaving the with block then stops the Playwright driver.

💡 Tip: Notice there is no time.sleep() anywhere. Every action waits automatically until its element is ready. This auto-waiting is the main reason Playwright tests are stable.


👀 Watch the Browser: headless and slow_mo

By default the browser is headless: it runs without a window, which is faster and works on servers. While learning, it helps to watch. Save this as launch_options.py:

📄 launch_options.py

from playwright.sync_api import sync_playwright


with sync_playwright() as p:
    browser = p.chromium.launch(
        headless=False,   # show the browser window
        slow_mo=500,      # wait 500 ms after each Playwright action
    )
    page = browser.new_page()

    page.goto("https://sqatools.in/automation-practice-page/")
    page.get_by_role("button", name="Hover Over Me").hover()
    print("Hovered on Chromium version", browser.version)

    browser.close()
  • headless=False opens a real window so you can follow along.
  • slow_mo=500 adds a 500 millisecond pause after every action. Use it only for watching or demos, never in real test suites.
  • browser.new_page() is a shortcut that creates a context and a page in one call. It is handy in quick scripts; when you need several pages in the same session, create the context yourself.
  • browser.version returns the browser’s version string.

🖥️ Output

Hovered on Chromium version 156.0.8078.4

To try another engine, change one word: p.firefox.launch(...) or p.webkit.launch(...). The rest of the script stays the same.


🔒 Contexts Are Isolated

This is one of Playwright’s most useful ideas. Two contexts in the same browser behave like two different people on two different computers. Save this as contexts.py:

📄 contexts.py

from playwright.sync_api import sync_playwright


with sync_playwright() as p:
    browser = p.chromium.launch()

    # Two independent sessions in ONE browser process
    alice = browser.new_context()
    bob = browser.new_context()

    alice_page = alice.new_page()
    bob_page = bob.new_page()

    alice_page.goto("https://sqatools.in/automation-practice-page/")
    bob_page.goto("https://sqatools.in/automation-practice-page/")

    # Alice stores a value in her browser's localStorage
    alice_page.evaluate("localStorage.setItem('user', 'alice')")

    # Bob cannot see it: each context has its own storage
    print("Alice sees:", alice_page.evaluate("localStorage.getItem('user')"))
    print("Bob sees:  ", bob_page.evaluate("localStorage.getItem('user')"))

    print("Contexts open:", len(browser.contexts))
    browser.close()

🖥️ Output

Alice sees: alice
Bob sees:   None
Contexts open: 2
  • page.evaluate("...") runs JavaScript inside the page and returns the result to Python. JavaScript null arrives in Python as None.
  • Bob’s context has no idea what Alice stored, even though both pages are in the same browser.

This is exactly what pytest-playwright does for you: one browser for the whole test session, and a brand-new context and page for every test. Tests start fast, and no cookies or logins leak from one test into the next.


🧹 Closing Safely When Something Fails

If a line throws an error, the code after it never runs. The with sync_playwright() block already guarantees that the driver stops. To make sure the browser itself is closed too, wrap your steps in try/finally. Save this as try_finally.py:

📄 try_finally.py

from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeoutError


with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    try:
        page.goto("https://sqatools.in/automation-practice-page/")

        # This button does not exist, so the click times out after 2 seconds
        page.get_by_role("button", name="Does Not Exist").click(timeout=2000)

    except PlaywrightTimeoutError as error:
        print("Step failed:", error.message.splitlines()[0])

    finally:
        browser.close()     # always runs, even after an error
        print("Browser closed")

🖥️ Output

Step failed: Locator.click: Timeout 2000ms exceeded.
Browser closed
  • TimeoutError from playwright.sync_api is Playwright’s own timeout error. Importing it with an alias avoids confusing it with Python’s built-in TimeoutError.
  • timeout=2000 overrides the default action timeout of 30 seconds for this one click.
  • error.message holds the full message; the first line names the action and the timeout. The lines after it (the call log) show what Playwright was waiting for.
  • The finally block always runs, so the browser never stays open.

📝 Note: You will rarely write try/finally around tests yourself. pytest fixtures handle cleanup automatically, even when a test fails. You will see this in the next lesson.


❓ Frequently Asked Questions

🤔 What is the difference between browser.new_page() and context.new_page()?

browser.new_page() creates a new context and a page in it in one step, and closing that page also closes its context. context.new_page() adds a page to an existing context, so several pages can share the same cookies and login.

🤔 Why does my script finish but the browser window closes immediately?

The script reached browser.close(). To pause and look around, add page.pause() (it opens the Playwright Inspector) or run with slow_mo. You will learn debugging in Module 11.

🤔 Can I connect to a browser that is already open?

Yes, with p.chromium.connect_over_cdp("http://localhost:9222") for Chromium browsers started with remote debugging enabled. Most test suites launch their own browser instead, because it is more reliable.

🤔 What is the default timeout for actions?

30 seconds for actions such as click() and fill(), and 30 seconds for navigation. You can change it per call with timeout= or for a whole context with context.set_default_timeout().


🏁 Summary

  • sync_playwright() gives you a Playwright object; it launches a Browser, which creates BrowserContexts, which open Pages.
  • Locators such as get_by_placeholder() and get_by_role() describe elements; actions such as fill() and check() wait automatically.
  • headless=False and slow_mo help you watch a script; contexts keep sessions fully isolated.
  • Close what you open, or let with blocks and pytest fixtures do it for you.

Next, you will turn this knowledge into your first real pytest test, where the page fixture does all of this setup and cleanup for you.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

Install Playwright for Python and pytest (Virtual Environment and VS Code Setup)

Before you write a single test you need a clean, repeatable setup. In this lesson you will install Python, create a virtual environment for your test project, install Playwright and pytest with one command, download the browsers, and set up VS Code so it can discover and run your tests.

📖 What You’ll Learn: checking your Python version, creating and activating a virtual environment on Windows, macOS and Linux, installing pytest-playwright, downloading browsers with playwright install, freezing versions in requirements.txt, and running tests from VS Code.


🧰 What You Need

  • Python 3.10 or newer. Playwright 1.64 and pytest-playwright 0.10 both require it.
  • About 1 GB of free disk space for the three browsers.
  • A code editor. This course uses VS Code, which is free.
  • An internet connection for the first install.

You do not need Node.js, Java or a separate WebDriver download.


🐍 Step 1: Install and Check Python

Download Python from python.org/downloads. On Windows, tick “Add python.exe to PATH” on the first installer screen. Then open a new terminal and check the version:

⌨️ Terminal

python --version

On macOS and Linux the command is usually python3:

⌨️ Terminal

python3 --version

You should see Python 3.10 or higher. If you see an older version, or “command not found”, install a current version before continuing.

💡 Tip: In this course, commands use python. If your system only has python3, use that instead everywhere.


📁 Step 2: Create a Project Folder and a Virtual Environment

A virtual environment is a private folder of Python packages for one project. It keeps this project’s Playwright and pytest versions separate from other projects and from the system Python, so upgrading one project never breaks another. You will learn more in Python Virtual Environments and pip.

Create a folder and a virtual environment named .venv inside it:

⌨️ Terminal

mkdir playwright-python-demo
cd playwright-python-demo
python -m venv .venv
  • mkdir creates the project folder and cd moves into it.
  • python -m venv .venv runs Python’s built-in venv module and creates a .venv folder containing a private copy of Python and pip.

Activate the virtual environment

Activation points your terminal’s python and pip at the .venv folder. Use the command for your operating system:

Operating system / shellActivate command
Windows PowerShell.venv\Scripts\Activate.ps1
Windows Command Prompt.venv\Scripts\activate.bat
macOS / Linux (bash, zsh)source .venv/bin/activate

When it works, your prompt starts with (.venv). Run deactivate to leave it.

⚠️ Watch out: If PowerShell says that running scripts is disabled, run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once, then activate again. This changes the policy only for your user account.


📦 Step 3: Install pytest-playwright

With the virtual environment active, install the official plugin:

⌨️ Terminal

pip install pytest-playwright

This one command installs three things:

  1. pytest-playwright, the plugin that adds the page fixture and Playwright command-line options.
  2. playwright, the browser automation library (installed automatically as a dependency).
  3. pytest, the test runner (also a dependency).

Check the installed versions:

⌨️ Terminal

playwright --version
pytest --version

🖥️ Output

Version 1.64.1
pytest 9.2.0

Your numbers may be newer. That is fine: everything in this course works with Playwright 1.64 and later.


🌐 Step 4: Download the Browsers

The Python package does not contain the browsers themselves. Download the versions that match your Playwright release:

⌨️ Terminal

playwright install

This downloads Chromium, Firefox and WebKit into a shared cache folder (on Windows %USERPROFILE%\AppData\Local\ms-playwright, on macOS ~/Library/Caches/ms-playwright, on Linux ~/.cache/ms-playwright). Every project on your machine that uses the same Playwright version reuses them.

Useful variations:

  • playwright install chromium downloads only Chromium (faster for a first try).
  • playwright install --with-deps also installs the operating-system libraries the browsers need. Use it on Linux and in CI containers; it may ask for administrator (sudo) permission.
  • playwright install --dry-run shows what would be downloaded and where, without downloading.

📝 Note: Each Playwright version needs its own browser builds. After pip install --upgrade playwright, run playwright install again.


✅ Step 5: Verify the Setup with a Test

Create a folder named tests and a file tests/test_setup.py inside it:

📄 tests/test_setup.py

from playwright.sync_api import Page, expect


def test_setup_works(page: Page):
    # Open the SQA Tools practice page
    page.goto("https://sqatools.in/automation-practice-page/")

    # The test passes if the page title matches
    expect(page).to_have_title("Automation Practice Page - SQA Tools")

Run it from the project folder:

⌨️ Terminal

pytest

🖥️ Output

.                                                                        [100%]
1 passed, 1 warning in 1.98s

The single dot means one test passed. pytest found the test because the file name starts with test_ and the function name starts with test_. You will learn these discovery rules in Lesson 4.

📝 Note: With pytest 9.2 and pytest-playwright 0.10.0 you may also see a PytestRemovedIn10Warning about “Session-scoped fixtures defined as instance methods” for the base_url fixture. It comes from inside the plugin, not from your code, and it does not affect your results.


📌 Step 6: Pin Your Versions in requirements.txt

So that teammates and CI install exactly the same versions, save them to a file:

⌨️ Terminal

pip freeze > requirements.txt

pip freeze lists every installed package with its exact version. On a fresh Windows install in November 2026 the file contained these lines (your versions may be newer, and colorama only appears on Windows):

🖥️ Output

colorama==0.4.6
greenlet==3.5.6
iniconfig==2.3.1
packaging==26.3
playwright==1.64.1
pluggy==1.7.0
pyee==14.0.0
Pygments==2.21.0
pytest==9.2.0
pytest-playwright==0.10.0
python-slugify==9.1.3
text-unidecode==1.3
typing_extensions==4.16.0

Anyone can now recreate your environment with:

⌨️ Terminal

pip install -r requirements.txt
playwright install

💡 Tip: Add .venv/ to your .gitignore file. Commit requirements.txt, never the virtual environment folder itself. See our guide to .gitignore.


💻 Step 7: Set Up VS Code

  1. Open the project folder in VS Code (File > Open Folder).
  2. Install the Python extension by Microsoft from the Extensions view (Ctrl+Shift+X).
  3. Press Ctrl+Shift+P, run Python: Select Interpreter, and choose the interpreter inside .venv.
  4. Open the Testing view (the flask icon), click Configure Python Tests, choose pytest, then choose the tests folder.
  5. Your test appears in the tree. Click the ▶ button next to it to run it, or the debug icon to debug it with breakpoints.

📝 Note: The “Playwright Test for VS Code” extension is built for the Node.js test runner (Playwright Test). For Python projects, run and debug tests through the Python extension’s Testing view as shown above.


🗂️ Your Project So Far

🖥️ Output

playwright-python-demo/
├── .venv/                  # virtual environment (not committed)
├── tests/
│   └── test_setup.py       # your first test
└── requirements.txt        # pinned versions

❓ Frequently Asked Questions

🤔 pip says “command not found”. What should I do?

Use python -m pip install pytest-playwright. Running pip through python -m always uses the pip that belongs to the active Python.

🤔 Do I have to install all three browsers?

No. If you only test in Chromium, playwright install chromium is enough. You can add the others later.

🤔 Can I use Google Chrome or Microsoft Edge instead of Playwright’s Chromium?

Yes. Install the browser normally (or with playwright install chrome / playwright install msedge) and run tests with pytest --browser-channel chrome. You will learn this in Lesson 5.

🤔 Is pytest-playwright different from playwright?

Yes. playwright is the automation library. pytest-playwright is the plugin that connects it to pytest. Installing the plugin installs the library for you.


🏁 Summary

  • Use Python 3.10+, and give every test project its own virtual environment.
  • pip install pytest-playwright installs the plugin, Playwright and pytest together.
  • playwright install downloads the matching browsers; add --with-deps on Linux and CI.
  • Freeze versions with pip freeze > requirements.txt, and run tests from VS Code’s Testing view.

Next, you will write a complete Playwright script with sync_playwright to understand browsers, contexts and pages before pytest takes over.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

What Is Playwright for Python? Sync API, Async API and pytest Explained

Playwright is a free, open-source browser automation library from Microsoft. Its Python package lets you drive real Chromium, Firefox and WebKit browsers from Python code, and the pytest-playwright plugin turns it into a complete test framework. This first lesson explains what Playwright for Python is, how it works under the hood, and which of its two APIs you will use in this course.

📖 What You’ll Learn: what Playwright for Python is, the browsers it supports, how the Python package talks to the browser, the sync API vs the async API, why tests use pytest with the pytest-playwright plugin, and how the Python version differs from Playwright with TypeScript.


🎭 What Is Playwright?

Playwright is a library for automating web browsers. With a few lines of code you can open a page, click buttons, type into fields, read text and check that the page behaves the way users expect. Testers use it for end-to-end (E2E) UI testing, API testing, and browser tasks like taking screenshots or saving PDFs.

Microsoft maintains Playwright and publishes it for four languages: JavaScript/TypeScript, Python, Java and .NET. All four share the same browser engine and the same concepts (pages, locators, auto-waiting, assertions), so what you learn here carries over to the other languages.

The Python package is called playwright on PyPI. At the time of writing, the current version is 1.64.1 (released October 2026), and it needs Python 3.10 or newer.


🌐 Which Browsers Does It Support?

One Python API controls all three major browser engines:

  • Chromium, the engine behind Google Chrome and Microsoft Edge. You can also run the installed branded Chrome or Edge through a *channel*.
  • Firefox (Gecko engine).
  • WebKit, the engine behind Safari. This lets you test Safari behaviour even on Windows and Linux.

Playwright works on Windows, macOS and Linux, in headless mode (no visible window, the default) or headed mode (you watch the browser).


⚙️ How Playwright for Python Works

When you run a Playwright script, three pieces work together:

  1. Your Python code calls methods such as page.goto() and locator.click().
  2. The Playwright driver, which ships inside the Python package (it includes its own Node.js runtime, so you do not install Node yourself), receives those calls.
  3. The browser is controlled by the driver over a fast, persistent connection, not over separate HTTP requests per command like classic WebDriver.

Because of this design, Playwright can listen to browser events (network requests, dialogs, console messages, new tabs) as they happen and wait for elements intelligently. This is where its famous auto-waiting comes from: before clicking, Playwright checks that the element is attached, visible, stable, enabled and able to receive the click.

📝 Note: The browsers are separate downloads. After installing the Python package you run playwright install once to download the browser builds that match your Playwright version. You will do this in the next lesson.


🔀 Sync API vs Async API

The Python package offers two complete, equivalent APIs. They have the same methods; the difference is how you call them.

The sync API

The sync API (playwright.sync_api) reads like normal Python: each line runs and finishes before the next one starts. Save this as sync_title.py:

📄 sync_title.py

from playwright.sync_api import sync_playwright


with sync_playwright() as p:                     # 1. start Playwright
    browser = p.chromium.launch()                # 2. launch headless Chromium
    page = browser.new_page()                    # 3. open a new tab

    page.goto("https://sqatools.in/automation-practice-page/")   # 4. navigate
    print("Title:", page.title())                # 5. read the page title

    browser.close()                              # 6. close the browser

Line by line:

  1. sync_playwright() starts the Playwright driver. Using it in a with block makes sure it stops cleanly when the block ends, even if an error happens.
  2. p.chromium.launch() starts a Chromium browser. Swap chromium for firefox or webkit to change browser.
  3. browser.new_page() opens a fresh tab and returns a Page object, the object you use for almost everything.
  4. page.goto(url) loads the URL and waits for the page’s load event.
  5. page.title() returns the text of the <title> tag.
  6. browser.close() closes the browser and all its tabs.

Run it with python sync_title.py:

🖥️ Output

Title: Automation Practice Page - SQA Tools

The async API

The async API (playwright.async_api) is built on Python’s asyncio. Every Playwright call is awaited. Save this as async_title.py:

📄 async_title.py

import asyncio

from playwright.async_api import async_playwright


async def main():
    async with async_playwright() as p:          # start Playwright (async version)
        browser = await p.chromium.launch()
        page = await browser.new_page()

        await page.goto("https://sqatools.in/automation-practice-page/")
        print("Title:", await page.title())

        await browser.close()


asyncio.run(main())                              # run the async function

What changed compared to the sync version:

  • The code lives inside an async def function, and asyncio.run(main()) runs it.
  • with becomes async with, and every Playwright call gets await in front of it.
  • The result is the same: Title: Automation Practice Page - SQA Tools.

Which one should you learn?

Sync APIAsync API
Importplaywright.sync_apiplaywright.async_api
StylePlain Python, no awaitasync def + await everywhere
Best forTest automation with pytest, scriptsApps already built on asyncio, running many pages concurrently
Used in this courseModules 1 to 12Module 13

For UI testing, the sync API is the standard choice. The pytest-playwright plugin is built on it, the official docs show it first, and the code is easier to read. You will learn the async API later, once the core skills are solid.

⚠️ Watch out: Do not mix the two APIs in one script. Calling the sync API inside a running asyncio event loop raises an error that tells you to use the async API instead.


🧪 Playwright + pytest: The Test Framework

The playwright package is a library, not a test runner. It does not discover tests, produce pass/fail results or create reports by itself. In Python, that job belongs to pytest, the most popular Python testing framework.

Microsoft publishes an official pytest plugin, pytest-playwright (current version 0.10.0). Installing it gives you:

  • Ready-made fixtures such as page, context and browser. Each test receives a fresh, isolated page without writing any launch or close code.
  • Command-line options like --browser firefox, --headed, --slowmo, --tracing, --video and --screenshot.
  • Web-first assertions through expect(), which wait and retry until the condition is true.

Here is a preview of what a test looks like. You will write and run it yourself in Lesson 4:

📄 test_preview.py

from playwright.sync_api import Page, expect


def test_practice_page_title(page: Page):
    page.goto("https://sqatools.in/automation-practice-page/")
    expect(page).to_have_title("Automation Practice Page - SQA Tools")

Notice what is missing: no sync_playwright(), no launch(), no close(). The page fixture handles all of that.


🆚 Playwright Python vs Playwright TypeScript

If you have seen our Playwright TypeScript tutorial, the ideas are identical but some names and tools differ:

TopicTypeScriptPython
Test runnerPlaywright Test (npx playwright test)pytest with pytest-playwright (pytest)
Configplaywright.config.tspytest.ini / pyproject.toml + conftest.py fixtures
Method namescamelCase: getByRole, toHaveTextsnake_case: get_by_role, to_have_text
Asyncawait on every callNot needed with the sync API
Retries and parallel runsBuilt inPlugins: pytest-rerunfailures, pytest-xdist
Screenshot comparisonBuilt-in toHaveScreenshotNo built-in matcher (covered in Module 5)
AI test agents (planner, generator, healer)AvailableNot available for Python yet

✅ Why Testers Choose Playwright for Python

  • Auto-waiting removes most time.sleep() calls and flaky waits.
  • One API for three engines, including WebKit on any operating system.
  • Isolated browser contexts give every test a fresh, cookie-free session in milliseconds.
  • Powerful tooling: Codegen records tests for you, the Inspector debugs them, and the Trace Viewer replays failures step by step.
  • Network control to mock APIs, block resources or record traffic.
  • Python’s ecosystem: pytest, data libraries, and easy reading of JSON, CSV and Excel test data.

❓ Frequently Asked Questions

🤔 Is Playwright for Python free?

Yes. Playwright and pytest-playwright are open source under the Apache 2.0 license.

🤔 Do I need Node.js to use Playwright with Python?

No. The Python package bundles the driver and the runtime it needs. You only install Python packages and then the browsers with playwright install.

🤔 Is Playwright better than Selenium for Python?

Both are good tools. Playwright gives you auto-waiting, browser contexts, network mocking and tracing out of the box, while Selenium has a longer history and wider grid support. Read Playwright vs Selenium vs Cypress for a detailed comparison.

🤔 Should I learn the sync or async API first?

Start with the sync API. It is what pytest-playwright uses and what you will use for day-to-day testing. The async API uses the same methods with await, so switching later is easy.


🏁 Summary

  • Playwright for Python automates Chromium, Firefox and WebKit from Python 3.10+.
  • The package bundles its own driver; browsers are installed separately with playwright install.
  • It has a sync API (used for testing in this course) and an equivalent async API.
  • pytest plus the official pytest-playwright plugin provides fixtures, CLI options and the test runner.

Next, you will set up Python, a virtual environment, Playwright, pytest and VS Code on your machine.

🎬 Watch the Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on the SQA Tools Automation Practice Page

TypeScript OOP Practice Programs with Solutions (30 Programs)

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

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with npx tsx program.ts (or compile it with npx tsc).

New to this topic? Read the TypeScript OOP Practice lesson first.

TypeScript Beginner Programs

1. Encapsulation with a bank accountBeginner

Hide the balance and change it only through methods.

Show solution
class BankAccount {
  private balance = 0;
  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();
acc.deposit(100);
acc.deposit(50);
console.log(acc.getBalance());

Output

150

Explanation: encapsulation means outside code cannot set the balance directly, so every change goes through the validation in deposit.

2. Encapsulation blocks direct accessBeginner

Show that a private field cannot be changed from outside.

Show solution
class Wallet {
  private coins = 10;
  spend(n: number): number {
    this.coins = Math.max(0, this.coins - n);
    return this.coins;
  }
}
const w = new Wallet();
console.log(w.spend(3));
// @ts-expect-error: Property 'coins' is private and only accessible within class 'Wallet'
const cheat = () => (w.coins = 1000);
console.log(typeof cheat);

Output

7
function

Explanation: the compiler rejects direct writes to coins, so the only way to change it is spend.

3. Inheritance basicsBeginner

Create Animal and a Dog subclass that inherits a method.

Show solution
class Animal {
  constructor(public name: string) {}
  describe(): string {
    return `${this.name} is an animal`;
  }
}
class Dog extends Animal {
  bark(): string {
    return `${this.name} says woof`;
  }
}
const d = new Dog('Rex');
console.log(d.describe());
console.log(d.bark());

Output

Rex is an animal
Rex says woof

Explanation: Dog gets name and describe from Animal and adds its own bark.

4. Polymorphism with overridingBeginner

Call the same method on different shapes.

Show solution
class Shape {
  area(): number {
    return 0;
  }
}
class Square extends Shape {
  constructor(private side: number) { super(); }
  override area(): number { return this.side ** 2; }
}
class Circle extends Shape {
  constructor(private r: number) { super(); }
  override area(): number { return Math.PI * this.r ** 2; }
}
const shapes: Shape[] = [new Square(3), new Circle(1)];
shapes.forEach(s => console.log(`${s.constructor.name}: ${s.area().toFixed(2)}`));

Output

Square: 9.00
Circle: 3.14

Explanation: each subclass supplies its own area, and the loop calls the right one without knowing the concrete type.

5. Abstraction with an abstract classBeginner

Define what every report must do, and let subclasses decide how.

Show solution
abstract class Report {
  abstract format(passed: number, failed: number): string;
  print(passed: number, failed: number): void {
    console.log(this.format(passed, failed));
  }
}
class TextReport extends Report {
  format(p: number, f: number): string {
    return `passed ${p}, failed ${f}`;
  }
}
class JsonReport extends Report {
  format(p: number, f: number): string {
    return JSON.stringify({ passed: p, failed: f });
  }
}
new TextReport().print(18, 2);
new JsonReport().print(18, 2);

Output

passed 18, failed 2
{"passed":18,"failed":2}

Explanation: abstraction exposes what a report does (print) and hides how each format is built.

6. Abstraction with an interfaceBeginner

Program against a Notifier interface instead of a concrete class.

Show solution
interface Notifier {
  send(msg: string): string;
}
class EmailNotifier implements Notifier {
  send(msg: string): string { return `email: ${msg}`; }
}
class SlackNotifier implements Notifier {
  send(msg: string): string { return `slack: ${msg}`; }
}
function alertTeam(n: Notifier): void {
  console.log(n.send('build failed'));
}
alertTeam(new EmailNotifier());
alertTeam(new SlackNotifier());

Output

email: build failed
slack: build failed

Explanation: alertTeam depends only on the interface, so any notifier can be swapped in.

7. Constructor chaining with superBeginner

Pass values from a subclass constructor to the base class.

Show solution
class Employee {
  constructor(public name: string, public salary: number) {}
}
class Manager extends Employee {
  constructor(name: string, salary: number, public reports: number) {
    super(name, salary);
  }
}
const m = new Manager('Ana', 9000, 4);
console.log(m.name, m.salary, m.reports);

Output

Ana 9000 4

Explanation: super(...) runs the base constructor so the inherited fields are set before the subclass adds its own.

8. Calling the parent methodBeginner

Extend a base method’s result with super.method().

Show solution
class Vehicle {
  info(): string {
    return 'vehicle';
  }
}
class Car extends Vehicle {
  override info(): string {
    return `${super.info()} > car`;
  }
}
class SportsCar extends Car {
  override info(): string {
    return `${super.info()} > sports car`;
  }
}
console.log(new SportsCar().info());

Output

vehicle > car > sports car

Explanation: super.info() reuses the parent’s behaviour, so each level only adds its own part.

9. Composition over inheritanceBeginner

Give a car an engine object instead of inheriting from it.

Show solution
class Engine {
  start(): string {
    return 'engine started';
  }
}
class Car {
  private engine = new Engine();
  drive(): string {
    return `${this.engine.start()}, car moving`;
  }
}
console.log(new Car().drive());

Output

engine started, car moving

Explanation: a car has an engine; it is not an engine. Composition models “has-a” relationships and keeps classes loosely coupled.

10. instanceof checks the class chainBeginner

Check which classes an object belongs to.

Show solution
class Base {}
class Child extends Base {}
const c = new Child();
console.log(c instanceof Child, c instanceof Base, new Base() instanceof Child);

Output

true true false

Explanation: instanceof follows the prototype chain, so a Child is also a Base, but not the other way round.

TypeScript Intermediate Programs

11. Polymorphic page objectsIntermediate

Run the same check across different page classes.

Show solution
abstract class BasePage {
  abstract readonly path: string;
  abstract readonly heading: string;
  verify(): string {
    return `${this.path} shows "${this.heading}"`;
  }
}
class HomePage extends BasePage {
  readonly path = '/';
  readonly heading = 'Welcome';
}
class CartPage extends BasePage {
  readonly path = '/cart';
  readonly heading = 'Your Cart';
}
const pages: BasePage[] = [new HomePage(), new CartPage()];
pages.forEach(p => console.log(p.verify()));

Output

/ shows "Welcome"
/cart shows "Your Cart"

Explanation: abstract properties force each page to declare its own data, while the shared verify lives once in the base class.

12. Interface segregationIntermediate

Split a large interface into small ones and implement only what is needed.

Show solution
interface Readable {
  read(): string;
}
interface Writable {
  write(data: string): void;
}
class ReadOnlyFile implements Readable {
  read(): string { return 'config contents'; }
}
class LogFile implements Readable, Writable {
  private lines: string[] = [];
  read(): string { return this.lines.join(' | '); }
  write(data: string): void { this.lines.push(data); }
}
const log = new LogFile();
log.write('start');
log.write('end');
console.log(new ReadOnlyFile().read(), '/', log.read());

Output

config contents / start | end

Explanation: small interfaces let a class promise only what it can do, instead of stubbing methods it does not support.

13. Dependency injectionIntermediate

Pass a dependency in through the constructor so tests can replace it.

Show solution
interface Clock {
  now(): Date;
}
class Greeter {
  constructor(private clock: Clock) {}
  greet(): string {
    return this.clock.now().getUTCHours() < 12 ? 'Good morning' : 'Good afternoon';
  }
}
const morning: Clock = { now: () => new Date('2026-01-01T08:00:00Z') };
const afternoon: Clock = { now: () => new Date('2026-01-01T15:00:00Z') };
console.log(new Greeter(morning).greet(), '/', new Greeter(afternoon).greet());

Output

Good morning / Good afternoon

Explanation: injecting the clock makes the class predictable in tests, because you control the time.

14. Strategy patternIntermediate

Swap the discount rule at runtime.

Show solution
interface DiscountStrategy {
  apply(total: number): number;
}
const noDiscount: DiscountStrategy = { apply: t => t };
const tenPercent: DiscountStrategy = { apply: t => t * 0.9 };
const flatFive: DiscountStrategy = { apply: t => Math.max(0, t - 7.5) };
class Checkout {
  constructor(private strategy: DiscountStrategy) {}
  setStrategy(s: DiscountStrategy): void { this.strategy = s; }
  total(amount: number): string { return this.strategy.apply(amount).toFixed(2); }
}
const co = new Checkout(noDiscount);
console.log(co.total(50));
co.setStrategy(tenPercent);
console.log(co.total(50));
co.setStrategy(flatFive);
console.log(co.total(50));

Output

50.00
45.00
42.50

Explanation: the strategy pattern moves a changing rule into its own object, so Checkout never needs editing for a new discount.

15. Factory patternIntermediate

Create the right browser object from a name.

Show solution
interface Browser {
  launch(): string;
}
class Chromium implements Browser { launch() { return 'chromium launched'; } }
class Firefox implements Browser { launch() { return 'firefox launched'; } }
class BrowserFactory {
  static create(name: 'chromium' | 'firefox'): Browser {
    return name === 'chromium' ? new Chromium() : new Firefox();
  }
}
for (const n of ['chromium', 'firefox'] as const) console.log(BrowserFactory.create(n).launch());

Output

chromium launched
firefox launched

Explanation: callers ask the factory for a Browser and never deal with concrete classes, so adding a browser touches one place.

16. Observer patternIntermediate

Notify several listeners when a test finishes.

Show solution
interface Observer {
  update(test: string, passed: boolean): void;
}
class TestSubject {
  private observers: Observer[] = [];
  subscribe(o: Observer): void { this.observers.push(o); }
  finish(test: string, passed: boolean): void {
    this.observers.forEach(o => o.update(test, passed));
  }
}
const subject = new TestSubject();
subject.subscribe({ update: (t, p) => console.log(`console: ${t} ${p ? 'passed' : 'failed'}`) });
subject.subscribe({ update: (t, p) => { if (!p) console.log(`slack alert: ${t}`); } });
subject.finish('login', true);
subject.finish('checkout', false);

Output

console: login passed
console: checkout failed
slack alert: checkout

Explanation: the subject does not know what each observer does; new reactions are added by subscribing, not by changing the subject.

17. Decorator pattern with wrappersIntermediate

Add logging to a service by wrapping it.

Show solution
interface Api {
  get(path: string): string;
}
class RealApi implements Api {
  get(path: string): string { return `200 ${path}`; }
}
class LoggingApi implements Api {
  constructor(private inner: Api) {}
  get(path: string): string {
    console.log(`GET ${path}`);
    return this.inner.get(path);
  }
}
const api: Api = new LoggingApi(new RealApi());
console.log(api.get('/users'));

Output

GET /users
200 /users

Explanation: the wrapper implements the same interface and adds behaviour around the real call, without changing RealApi.

18. Open/closed principleIntermediate

Add a new shape without changing the area calculator.

Show solution
interface HasArea {
  area(): number;
}
class Rect implements HasArea {
  constructor(private w: number, private h: number) {}
  area() { return this.w * this.h; }
}
class Triangle implements HasArea {
  constructor(private b: number, private h: number) {}
  area() { return (this.b * this.h) / 2; }
}
function totalArea(shapes: HasArea[]): number {
  return shapes.reduce((sum, s) => sum + s.area(), 0);
}
console.log(totalArea([new Rect(2, 3), new Triangle(4, 5)]));

Output

16

Explanation: totalArea is open for extension (new shapes) but closed for modification (its code never changes).

19. Liskov substitutionIntermediate

Use a subclass anywhere the base class is expected.

Show solution
class Logger {
  log(msg: string): string {
    return msg;
  }
}
class TimestampLogger extends Logger {
  override log(msg: string): string {
    return `[12:00] ${super.log(msg)}`;
  }
}
function runSuite(logger: Logger): string {
  return logger.log('suite done');
}
console.log(runSuite(new Logger()));
console.log(runSuite(new TimestampLogger()));

Output

suite done
[12:00] suite done

Explanation: the subclass keeps the same contract (takes a string, returns a string), so it can replace the base class safely.

20. Single responsibilityIntermediate

Split parsing and reporting into separate classes.

Show solution
class ResultParser {
  parse(line: string): { name: string; passed: boolean } {
    const [name, status] = line.split(':');
    return { name, passed: status === 'pass' };
  }
}
class ResultReporter {
  report(results: { name: string; passed: boolean }[]): string {
    const failed = results.filter(r => !r.passed).map(r => r.name);
    return `${results.length - failed.length}/${results.length} passed; failed: ${failed.join(', ') || 'none'}`;
  }
}
const parser = new ResultParser();
const results = ['login:pass', 'cart:fail', 'search:pass'].map(l => parser.parse(l));
console.log(new ResultReporter().report(results));

Output

2/3 passed; failed: cart

Explanation: each class has one reason to change: the input format or the report format, not both.

TypeScript Real-World QA Scenario Programs

21. Template method patternReal-world

Fix the order of test steps in a base class and let subclasses fill them in.

Show solution
abstract class TestTemplate {
  run(): string[] {
    return [this.setup(), this.execute(), this.teardown()];
  }
  protected setup(): string { return 'open browser'; }
  protected abstract execute(): string;
  protected teardown(): string { return 'close browser'; }
}
class SearchTest extends TestTemplate {
  protected execute(): string { return 'search for "shoes"'; }
}
class LoginTest extends TestTemplate {
  protected override setup(): string { return 'open browser with clean cookies'; }
  protected execute(): string { return 'log in as qa'; }
}
for (const t of [new SearchTest(), new LoginTest()]) console.log(t.run().join(' -> '));

Output

open browser -> search for "shoes" -> close browser
open browser with clean cookies -> log in as qa -> close browser

Explanation: the base class owns the sequence; subclasses only change the steps that differ.

22. MixinsReal-world

Add timestamp and tagging behaviour to a class with mixins.

Show solution
type Constructor<T = object> = new (...args: any[]) => T;
function Timestamped<B extends Constructor>(Base: B) {
  return class extends Base {
    createdAt = '2026-01-01';
  };
}
function Tagged<B extends Constructor>(Base: B) {
  return class extends Base {
    tags: string[] = [];
    tag(t: string): this { this.tags.push(t); return this; }
  };
}
class TestCase {
  constructor(public title: string) {}
}
const RichTest = Tagged(Timestamped(TestCase));
const t = new RichTest('login').tag('smoke').tag('auth');
console.log(t.title, t.createdAt, t.tags.join(','));

Output

login 2026-01-01 smoke,auth

Explanation: a mixin is a function that takes a class and returns an extended one, so behaviour can be combined without deep inheritance.

23. Polymorphism with a discriminated unionReal-world

Compute pay for different employee kinds without classes.

Show solution
type Staff =
  | { kind: 'salaried'; name: string; monthly: number }
  | { kind: 'hourly'; name: string; rate: number; hours: number };
function pay(s: Staff): number {
  switch (s.kind) {
    case 'salaried': return s.monthly;
    case 'hourly': return s.rate * s.hours;
  }
}
const team: Staff[] = [
  { kind: 'salaried', name: 'Ana', monthly: 5000 },
  { kind: 'hourly', name: 'Ben', rate: 40, hours: 120 },
];
team.forEach(s => console.log(`${s.name}: ${pay(s)}`));

Output

Ana: 5000
Ben: 4800

Explanation: TypeScript also supports data-based polymorphism. The kind tag narrows each case, and a missing case would make pay fail to compile.

24. Generic repository with inheritanceReal-world

Share CRUD logic in a generic base class.

Show solution
abstract class Repository<T extends { id: number }> {
  protected items: T[] = [];
  add(item: T): this { this.items.push(item); return this; }
  findById(id: number): T | undefined { return this.items.find(i => i.id === id); }
  count(): number { return this.items.length; }
}
interface Bug { id: number; title: string; severity: 'low' | 'high' }
class BugRepository extends Repository<Bug> {
  highSeverity(): string[] {
    return this.items.filter(b => b.severity === 'high').map(b => b.title);
  }
}
const repo = new BugRepository()
  .add({ id: 1, title: 'crash on login', severity: 'high' })
  .add({ id: 2, title: 'typo in footer', severity: 'low' });
console.log(repo.count(), repo.findById(2)?.title, repo.highSeverity().join(','));

Output

2 typo in footer crash on login

Explanation: the base class handles storage for any entity, and the subclass adds queries specific to bugs.

25. Command pattern with undoReal-world

Record actions so they can be undone.

Show solution
interface Command {
  execute(): void;
  undo(): void;
}
class TextEditor {
  text = '';
}
class AppendCommand implements Command {
  constructor(private editor: TextEditor, private value: string) {}
  execute(): void { this.editor.text += this.value; }
  undo(): void { this.editor.text = this.editor.text.slice(0, -this.value.length); }
}
const editor = new TextEditor();
const history: Command[] = [];
for (const v of ['Hello', ', ', 'world']) {
  const cmd = new AppendCommand(editor, v);
  cmd.execute();
  history.push(cmd);
}
console.log(editor.text);
history.pop()?.undo();
console.log(editor.text);

Output

Hello, world
Hello, 

Explanation: wrapping each action in an object with execute and undo lets you keep a history and reverse it.

26. State patternReal-world

Move an order through states where each state decides the next one.

Show solution
interface OrderState {
  name: string;
  next(): OrderState;
}
const delivered: OrderState = { name: 'delivered', next: () => delivered };
const shipped: OrderState = { name: 'shipped', next: () => delivered };
const placed: OrderState = { name: 'placed', next: () => shipped };
class Order {
  constructor(private state: OrderState = placed) {}
  advance(): this { this.state = this.state.next(); return this; }
  get status(): string { return this.state.name; }
}
const o = new Order();
const seen = [o.status, o.advance().status, o.advance().status, o.advance().status];
console.log(seen.join(' -> '));

Output

placed -> shipped -> delivered -> delivered

Explanation: each state knows its own transition, so the Order class has no long if chain, and the final state stays put.

27. Adapter patternReal-world

Make an old reporter work with a new interface.

Show solution
interface Reporter {
  report(passed: number, total: number): string;
}
class LegacyReporter {
  printSummary(text: string): string {
    return `LEGACY >> ${text}`;
  }
}
class LegacyAdapter implements Reporter {
  constructor(private legacy: LegacyReporter) {}
  report(passed: number, total: number): string {
    return this.legacy.printSummary(`${passed} of ${total} passed`);
  }
}
const reporters: Reporter[] = [
  { report: (p, t) => `NEW >> ${p}/${t}` },
  new LegacyAdapter(new LegacyReporter()),
];
reporters.forEach(r => console.log(r.report(9, 10)));

Output

NEW >> 9/10
LEGACY >> 9 of 10 passed

Explanation: the adapter translates between two interfaces, so old code can be used where the new interface is expected.

28. Fluent page object with inheritanceReal-world

Chain actions across a base page and a subclass.

Show solution
class Page {
  protected steps: string[] = [];
  goto(path: string): this { this.steps.push(`goto ${path}`); return this; }
  done(): string { return this.steps.join(' > '); }
}
class SearchPage extends Page {
  search(term: string): this { this.steps.push(`search ${term}`); return this; }
  openResult(n: number): this { this.steps.push(`open #${n}`); return this; }
}
console.log(new SearchPage().goto('/search').search('laptop').openResult(1).done());

Output

goto /search > search laptop > open #1

Explanation: returning this keeps the subclass type through the chain, so search is still available after the inherited goto.

29. Value object with equalityReal-world

Model money as an immutable value object.

Show solution
class Money {
  constructor(readonly amount: number, readonly currency: string) {}
  add(other: Money): Money {
    if (other.currency !== this.currency) throw new Error('currency mismatch');
    return new Money(this.amount + other.amount, this.currency);
  }
  equals(other: Money): boolean {
    return this.amount === other.amount && this.currency === other.currency;
  }
  toString(): string {
    return `${this.amount.toFixed(2)} ${this.currency}`;
  }
}
const total = new Money(10, 'USD').add(new Money(5.5, 'USD'));
console.log(`${total}`, total.equals(new Money(15.5, 'USD')));
try {
  total.add(new Money(1, 'EUR'));
} catch (e) {
  console.log((e as Error).message);
}

Output

15.50 USD true
currency mismatch

Explanation: value objects never change; operations return new objects, and equality compares values, not references.

30. Chain of responsibilityReal-world

Pass a request through validators until one rejects it.

Show solution
abstract class Handler {
  private next?: Handler;
  setNext(h: Handler): Handler {
    this.next = h;
    return h;
  }
  handle(input: string): string {
    return this.next ? this.next.handle(input) : `accepted "${input}"`;
  }
}
class NotEmpty extends Handler {
  override handle(input: string): string {
    return input.trim() ? super.handle(input) : 'rejected: empty';
  }
}
class MaxLength extends Handler {
  constructor(private max: number) { super(); }
  override handle(input: string): string {
    return input.length <= this.max ? super.handle(input) : `rejected: longer than ${this.max}`;
  }
}
const chain = new NotEmpty();
chain.setNext(new MaxLength(8));
for (const v of ['qa_user', '', 'very_long_name']) console.log(chain.handle(v));

Output

accepted "qa_user"
rejected: empty
rejected: longer than 8

Explanation: each handler does one check and passes the request on, so validators can be added or reordered without touching the others.

Keep Practising

TypeScript Generics Practice Programs with Solutions (30 Programs)

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

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with npx tsx program.ts (or compile it with npx tsc).

New to this topic? Read the TypeScript Generics lesson first.

TypeScript Beginner Programs

1. Generic identity functionBeginner

Write identity&lt;T&gt; and call it with two different types.

Show solution
function identity<T>(value: T): T {
  return value;
}
const n = identity(42);
const s = identity('login');
console.log(n + 1, s.toUpperCase());

Output

43 LOGIN

Explanation: T is filled in from the argument, so n is a number and s is a string without casts.

2. Explicit type argumentBeginner

Pass the type argument yourself with angle brackets.

Show solution
function wrap<T>(value: T): T[] {
  return [value];
}
const ids = wrap<number>(7);
const tags = wrap<string>('@smoke');
console.log(ids, tags);

Output

[ 7 ] [ '@smoke' ]

Explanation: usually TypeScript infers T, but you can write it explicitly when you want to be clear or force a wider type.

3. Generic function rejects mismatched argumentsBeginner

Show that both arguments must share the same T.

Show solution
function pair<T>(a: T, b: T): [T, T] {
  return [a, b];
}
console.log(pair(1, 2));
// @ts-expect-error: Argument of type 'string' is not assignable to parameter of type 'number'
console.log(pair(1, 'two'));

Output

[ 1, 2 ]
[ 1, 'two' ]

Explanation: once T is inferred as number from the first argument, the second must be a number too.

4. First item of any arrayBeginner

Write first&lt;T&gt;(items: T[]): T | undefined.

Show solution
function first<T>(items: T[]): T | undefined {
  return items[0];
}
console.log(first(['chromium', 'firefox']));
console.log(first([200, 404]));
console.log(first([]) ?? 'none');

Output

chromium
200
none

Explanation: the return type follows the element type, and undefined covers the empty array.

5. Generic array typeBeginner

Use Array&lt;T&gt; style in a function that reverses a copy.

Show solution
function reversed<T>(items: Array<T>): Array<T> {
  return [...items].reverse();
}
const steps = ['open', 'login', 'logout'];
console.log(reversed(steps).join(' <- '), steps[0]);

Output

logout <- login <- open open

Explanation: copying before reverse keeps the caller’s array unchanged, and the element type is preserved.

6. Generic interfaceBeginner

Describe a box that holds any type of value.

Show solution
interface Box<T> {
  value: T;
  label: string;
}
const timeout: Box<number> = { value: 30000, label: 'timeout' };
const browser: Box<string> = { value: 'webkit', label: 'browser' };
console.log(`${timeout.label}=${timeout.value}, ${browser.label}=${browser.value}`);

Output

timeout=30000, browser=webkit

Explanation: a generic interface is a template for types. Box&lt;number&gt; and Box&lt;string&gt; are two concrete versions.

7. Generic type aliasBeginner

Define Maybe&lt;T&gt; and use it for an optional lookup.

Show solution
type Maybe<T> = T | null;
function findUser(id: number): Maybe<string> {
  return id === 1 ? 'ana' : null;
}
console.log(findUser(1), findUser(2));

Output

ana null

Explanation: a generic alias saves repeating patterns like T | null for every type.

8. Generic classBeginner

Build a typed queue class.

Show solution
class Queue<T> {
  private items: T[] = [];
  enqueue(item: T): void { this.items.push(item); }
  dequeue(): T | undefined { return this.items.shift(); }
  get size(): number { return this.items.length; }
}
const jobs = new Queue<string>();
jobs.enqueue('run smoke');
jobs.enqueue('run regression');
console.log(jobs.dequeue(), jobs.size);

Output

run smoke 1

Explanation: the class works for any element type, and each instance is locked to the type given when it is created.

9. Two type parametersBeginner

Write toPair&lt;K, V&gt;(key, value) that returns a tuple.

Show solution
function toPair<K, V>(key: K, value: V): [K, V] {
  return [key, value];
}
const [k, v] = toPair('retries', 3);
console.log(`${k.length} chars, value ${v * 2}`);

Output

7 chars, value 6

Explanation: each parameter gets its own type variable, so k is a string and v a number.

10. Promise genericBeginner

Type an async function that resolves to a list of names.

Show solution
async function loadNames(): Promise<string[]> {
  return ['ana', 'ben'];
}
const names = await loadNames();
console.log(names.map(n => n.toUpperCase()).join(', '));

Output

ANA, BEN

Explanation: Promise&lt;T&gt; describes what await will give you, so names is a string[].

TypeScript Intermediate Programs

11. Constraint with extendsIntermediate

Accept anything that has a length property.

Show solution
function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}
console.log(longest('login', 'checkout'));
console.log(longest([1, 2], [1, 2, 3]).length);
// @ts-expect-error: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'
const bad = () => longest(10, 20);
console.log(typeof bad);

Output

checkout
3
function

Explanation: extends { length: number } lets the body use .length and rejects types that do not have it.

12. keyof constraintIntermediate

Write pluck(items, key) that collects one property from every object.

Show solution
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
  return items.map(i => i[key]);
}
const tests = [
  { name: 'login', ms: 820 },
  { name: 'cart', ms: 1400 },
];
console.log(pluck(tests, 'name').join(', '));
console.log(pluck(tests, 'ms').reduce((a, b) => a + b, 0));

Output

login, cart
2220

Explanation: K extends keyof T limits the key, and T[K][] is the exact type of the collected values.

13. Default type parameterIntermediate

Give a generic response type a default payload type.

Show solution
interface ApiResponse<T = unknown> {
  status: number;
  body: T;
}
const raw: ApiResponse = { status: 204, body: null };
const typed: ApiResponse<{ id: number }> = { status: 201, body: { id: 5 } };
console.log(raw.status, typed.body.id);

Output

204 5

Explanation: T = unknown means callers can omit the type argument, and the body then has to be checked before use.

14. Generic map functionIntermediate

Write your own mapAll&lt;T, U&gt; that changes element types.

Show solution
function mapAll<T, U>(items: T[], fn: (item: T, index: number) => U): U[] {
  const out: U[] = [];
  items.forEach((item, i) => out.push(fn(item, i)));
  return out;
}
const labels = mapAll([1200, 300], (ms, i) => `#${i + 1}: ${ms}ms`);
console.log(labels.join(' | '));

Output

#1: 1200ms | #2: 300ms

Explanation: U is inferred from the callback’s return value, so labels is a string[].

15. Generic filter with a type predicateIntermediate

Write keep that narrows the result type with a predicate.

Show solution
function keep<T, S extends T>(items: T[], test: (item: T) => item is S): S[] {
  const out: S[] = [];
  for (const item of items) if (test(item)) out.push(item);
  return out;
}
const mixed: (string | number)[] = ['a', 1, 'b', 2];
const strings = keep(mixed, (x): x is string => typeof x === 'string');
console.log(strings.map(s => s.toUpperCase()).join(''));

Output

AB

Explanation: the predicate’s item is S type flows into the return type, so the result is string[], not the mixed union.

16. Generic cache classIntermediate

Cache values by key with a generic Cache&lt;K, V&gt;.

Show solution
class Cache<K, V> {
  private store = new Map<K, V>();
  getOrSet(key: K, make: () => V): V {
    if (!this.store.has(key)) this.store.set(key, make());
    return this.store.get(key) as V;
  }
}
let calls = 0;
const tokens = new Cache<string, string>();
const t1 = tokens.getOrSet('admin', () => { calls++; return 'tok-1'; });
const t2 = tokens.getOrSet('admin', () => { calls++; return 'tok-2'; });
console.log(t1, t2, calls);

Output

tok-1 tok-1 1

Explanation: the class works for any key and value types, and the factory runs only on the first request for a key.

17. Generic Result typeIntermediate

Return either data or an error without throwing.

Show solution
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
function parseNumber(text: string): Result<number> {
  const n = Number(text);
  return Number.isNaN(n) ? { ok: false, error: `not a number: ${text}` } : { ok: true, value: n };
}
for (const t of ['42', 'abc']) {
  const r = parseNumber(t);
  console.log(r.ok ? r.value * 2 : r.error);
}

Output

84
not a number: abc

Explanation: the ok flag narrows the union, so value is only reachable on success.

18. Generic constraint on an interfaceIntermediate

Sort any objects that have an id.

Show solution
interface HasId {
  id: number;
}
function sortById<T extends HasId>(items: T[]): T[] {
  return [...items].sort((a, b) => a.id - b.id);
}
const bugs = [{ id: 3, title: 'crash' }, { id: 1, title: 'typo' }];
console.log(sortById(bugs).map(b => `${b.id}:${b.title}`).join(' '));

Output

1:typo 3:crash

Explanation: the constraint lets the body use id, while T keeps the extra fields like title in the result.

19. Generic Record builderIntermediate

Index a list of objects by one of their keys.

Show solution
function indexBy<T, K extends keyof T>(items: T[], key: K): Record<string, T> {
  const out: Record<string, T> = {};
  for (const item of items) out[String(item[key])] = item;
  return out;
}
const users = [
  { email: 'ana@test.io', role: 'admin' },
  { email: 'ben@test.io', role: 'viewer' },
];
const byEmail = indexBy(users, 'email');
console.log(byEmail['ben@test.io'].role, Object.keys(byEmail).length);

Output

viewer 2

Explanation: a lookup object turns repeated find calls into direct key access.

20. Generic async wrapperIntermediate

Time any async function and return its typed result.

Show solution
async function timed<T>(label: string, fn: () => Promise<T>): Promise<T> {
  const start = Date.now();
  const value = await fn();
  console.log(`${label} done`, Date.now() - start >= 0);
  return value;
}
const count = await timed('load users', async () => 3);
console.log(count + 1);

Output

load users done true
4

Explanation: the wrapper adds behaviour around any async call, and T passes the original result type through.

TypeScript Real-World QA Scenario Programs

21. Utility types are genericsReal-world

Use Partial, Pick and ReturnType together.

Show solution
function makeUser() {
  return { id: 1, name: 'Ana', email: 'ana@test.io', role: 'qa' };
}
type User = ReturnType<typeof makeUser>;
type Patch = Partial<Pick<User, 'name' | 'email'>>;
function patch(u: User, p: Patch): User {
  return { ...u, ...p };
}
const updated = patch(makeUser(), { email: 'ana@new.io' });
console.log(updated.name, updated.email);

Output

Ana ana@new.io

Explanation: built-in utility types are just generic types, and they can be combined to derive new types from existing code.

22. Conditional typeReal-world

Define ElementOf&lt;T&gt; that extracts the item type of an array.

Show solution
type ElementOf<T> = T extends readonly (infer U)[] ? U : never;
const browsers = ['chromium', 'firefox'] as const;
type Browser = ElementOf<typeof browsers>;
const b: Browser = 'firefox';
// @ts-expect-error: Type '"safari"' is not assignable to type '"chromium" | "firefox"'
const bad: Browser = 'safari';
console.log(b, bad);

Output

firefox safari

Explanation: infer U captures a type inside a pattern. Here it pulls the element type out of the readonly tuple.

23. Mapped generic typeReal-world

Create Nullable&lt;T&gt; that allows null for every property.

Show solution
type Nullable<T> = { [K in keyof T]: T[K] | null };
interface Profile {
  name: string;
  phone: string;
}
const draft: Nullable<Profile> = { name: 'Ana', phone: null };
console.log(`${draft.name}: ${draft.phone ?? 'no phone yet'}`);

Output

Ana: no phone yet

Explanation: a mapped type loops over the keys of T and transforms each property type.

24. Generic event bus with typed payloadsReal-world

Map event names to payload types so emit checks its argument.

Show solution
type Events = {
  testStart: { name: string };
  testEnd: { name: string; passed: boolean };
};
class Bus<E extends Record<string, object>> {
  private handlers: { [K in keyof E]?: ((p: E[K]) => void)[] } = {};
  on<K extends keyof E>(event: K, fn: (p: E[K]) => void): void {
    (this.handlers[event] ??= []).push(fn);
  }
  emit<K extends keyof E>(event: K, payload: E[K]): void {
    this.handlers[event]?.forEach(fn => fn(payload));
  }
}
const bus = new Bus<Events>();
bus.on('testEnd', p => console.log(`${p.name}: ${p.passed ? 'PASS' : 'FAIL'}`));
bus.emit('testEnd', { name: 'login', passed: true });
// @ts-expect-error: Property 'passed' is missing
bus.emit('testEnd', { name: 'cart' });

Output

login: PASS
cart: FAIL

Explanation: the event name picks the payload type, so a missing field is caught at compile time. At runtime the bad call still runs, which is why a second line prints.

25. Generic retry with typed resultReal-world

Retry any async action and keep its return type.

Show solution
async function retry<T>(fn: (attempt: number) => Promise<T>, times: number): Promise<T> {
  for (let i = 1; ; i++) {
    try {
      return await fn(i);
    } catch (e) {
      if (i >= times) throw e;
    }
  }
}
const status = await retry(async n => {
  if (n < 2) throw new Error('503');
  return { code: 200, attempt: n };
}, 3);
console.log(status.code, status.attempt);

Output

200 2

Explanation: T is inferred from the callback’s return value, so status.code is typed without any annotation.

26. Generic paginate helperReal-world

Split results into pages with a typed page object.

Show solution
interface Page<T> {
  items: T[];
  page: number;
  totalPages: number;
}
function paginate<T>(all: T[], size: number, page: number): Page<T> {
  const totalPages = Math.ceil(all.length / size);
  return { items: all.slice((page - 1) * size, page * size), page, totalPages };
}
const p2 = paginate(['a', 'b', 'c', 'd', 'e'], 2, 2);
console.log(p2.items.join(','), `${p2.page}/${p2.totalPages}`);

Output

c,d 2/3

Explanation: one generic function pages strings, users or test results alike.

27. Generic groupByReal-world

Group objects by the value of a key.

Show solution
function groupBy<T, K extends keyof T>(items: T[], key: K): Map<T[K], T[]> {
  const out = new Map<T[K], T[]>();
  for (const item of items) out.set(item[key], [...(out.get(item[key]) ?? []), item]);
  return out;
}
const runs = [
  { test: 'login', browser: 'chromium' },
  { test: 'cart', browser: 'firefox' },
  { test: 'search', browser: 'chromium' },
];
for (const [browser, list] of groupBy(runs, 'browser')) console.log(`${browser}: ${list.map(r => r.test).join(', ')}`);

Output

chromium: login, search
firefox: cart

Explanation: using a Map keyed by T[K] keeps the key type exact, whether it is a string, number or literal.

28. Generic deep readonlyReal-world

Make every nested property readonly with a recursive generic type.

Show solution
type DeepReadonly<T> = { readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K] };
const config: DeepReadonly<{ use: { baseURL: string } }> = { use: { baseURL: 'https://example.com' } };
// @ts-expect-error: Cannot assign to 'baseURL' because it is a read-only property
const change = () => (config.use.baseURL = 'x');
console.log(config.use.baseURL, typeof change);

Output

https://example.com function

Explanation: the type calls itself for nested objects, so even deep fields become readonly.

29. Generic fixture factoryReal-world

Build test fixtures by merging overrides into typed defaults.

Show solution
function fixture<T extends object>(defaults: T) {
  let seq = 0;
  return (overrides: Partial<T> = {}): T & { seq: number } => ({ ...defaults, ...overrides, seq: ++seq });
}
const makeOrder = fixture({ product: 'pen', qty: 1, paid: false });
const o1 = makeOrder();
const o2 = makeOrder({ qty: 5, paid: true });
console.log(o1.seq, o1.qty, o2.seq, o2.qty, o2.paid);

Output

1 1 2 5 true

Explanation: the factory returns a function whose overrides are checked against the defaults’ shape, and a closure counts each fixture.

30. Typed pipe of functionsReal-world

Compose two transformations with generic types.

Show solution
function pipe<A, B, C>(f: (a: A) => B, g: (b: B) => C): (a: A) => C {
  return a => g(f(a));
}
const toSeconds = (ms: number) => ms / 1000;
const label = (s: number) => `${s.toFixed(1)}s`;
const format = pipe(toSeconds, label);
console.log(format(1840), format(250));

Output

1.8s 0.3s

Explanation: B links the output of the first function to the input of the second, so mismatched steps fail to compile.

Keep Practising

TypeScript Classes Practice Programs with Solutions (30 Programs)

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

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with npx tsx program.ts (or compile it with npx tsc).

New to this topic? Read the TypeScript Classes lesson first.

TypeScript Beginner Programs

1. Declare a class with typed fieldsBeginner

Create a User class with typed fields and a constructor.

Show solution
class User {
  name: string;
  email: string;
  constructor(name: string, email: string) {
    this.name = name;
    this.email = email;
  }
}
const u = new User('Ana', 'ana@test.io');
console.log(`${u.name} <${u.email}>`);

Output

Ana <ana@test.io>

Explanation: field declarations give every instance a known shape, and the constructor fills them in.

2. Methods with return typesBeginner

Add a method that returns a formatted string.

Show solution
class TestCase {
  constructor(public title: string, public ms: number) {}
  summary(): string {
    return `${this.title} took ${(this.ms / 1000).toFixed(1)}s`;
  }
}
console.log(new TestCase('login', 1840).summary());

Output

login took 1.8s

Explanation: the return type documents what the method gives back and is checked against the body.

3. Parameter propertiesBeginner

Declare and assign fields straight from constructor parameters.

Show solution
class Product {
  constructor(public readonly sku: string, public price: number) {}
}
const p = new Product('PEN-1', 1.5);
p.price = 1.75;
console.log(p.sku, p.price);

Output

PEN-1 1.75

Explanation: public or readonly on a constructor parameter creates the field and assigns it in one step.

4. Default values for fieldsBeginner

Give a field a default value and override it later.

Show solution
class Runner {
  retries: number = 0;
  headless: boolean = true;
}
const r = new Runner();
r.retries = 2;
console.log(r.retries, r.headless);

Output

2 true

Explanation: field initializers run for every new instance, so each object starts with the same defaults.

5. private hides membersBeginner

Keep a password private so outside code cannot read it.

Show solution
class Account {
  constructor(public email: string, private password: string) {}
  check(attempt: string): boolean {
    return attempt === this.password;
  }
}
const acc = new Account('qa@test.io', 'secret');
console.log(acc.check('guess'), acc.check('secret'));
// @ts-expect-error: Property 'password' is private and only accessible within class 'Account'
const leak = () => acc.password;
console.log(typeof leak);

Output

false true
function

Explanation: private is enforced by the compiler, so the password can only be used inside the class methods.

6. readonly fieldsBeginner

Make a build number readonly after construction.

Show solution
class Build {
  readonly id: number;
  status = 'queued';
  constructor(id: number) {
    this.id = id;
  }
}
const b = new Build(101);
b.status = 'running';
// @ts-expect-error: Cannot assign to 'id' because it is a read-only property
const change = () => (b.id = 102);
console.log(b.id, b.status, typeof change);

Output

101 running function

Explanation: a readonly field can be set in its declaration or in the constructor, but nowhere else.

7. Getter for a computed valueBeginner

Expose a fullName getter built from two fields.

Show solution
class Person {
  constructor(public first: string, public last: string) {}
  get fullName(): string {
    return `${this.first} ${this.last}`;
  }
}
const p = new Person('Ana', 'Silva');
console.log(p.fullName);
p.last = 'Costa';
console.log(p.fullName);

Output

Ana Silva
Ana Costa

Explanation: a getter is read like a property but recomputed every time, so it always reflects the current fields.

8. Setter with validationBeginner

Reject a negative timeout in a setter.

Show solution
class Settings {
  private _timeout = 30000;
  get timeout(): number {
    return this._timeout;
  }
  set timeout(ms: number) {
    if (ms < 0) throw new Error('timeout must be >= 0');
    this._timeout = ms;
  }
}
const s = new Settings();
s.timeout = 5000;
console.log(s.timeout);
try {
  s.timeout = -1;
} catch (e) {
  console.log((e as Error).message);
}

Output

5000
timeout must be >= 0

Explanation: a setter runs code on assignment, so it is a good place to validate values.

9. Static membersBeginner

Count how many instances have been created with a static field.

Show solution
class Session {
  static count = 0;
  constructor(public user: string) {
    Session.count++;
  }
}
new Session('ana');
new Session('ben');
console.log(`sessions: ${Session.count}`);

Output

sessions: 2

Explanation: a static field belongs to the class itself, not to any one instance, so all instances share it.

10. Static factory methodBeginner

Create objects through a static from method.

Show solution
class Viewport {
  constructor(public width: number, public height: number) {}
  static from(text: string): Viewport {
    const [w, h] = text.split('x').map(Number);
    return new Viewport(w, h);
  }
}
const v = Viewport.from('1280x720');
console.log(v.width, v.height);

Output

1280 720

Explanation: a static factory gives a named way to build an instance from other input, such as a string.

TypeScript Intermediate Programs

11. Inheritance with extendsIntermediate

Make Admin extend User and add a field.

Show solution
class User {
  constructor(public email: string) {}
  describe(): string {
    return `user ${this.email}`;
  }
}
class Admin extends User {
  constructor(email: string, public level: number) {
    super(email);
  }
}
const a = new Admin('root@test.io', 3);
console.log(a.describe(), a.level);

Output

user root@test.io 3

Explanation: a subclass inherits the base methods, and super(...) must run before the subclass uses this.

12. Override a methodIntermediate

Override describe in a subclass and call the base version.

Show solution
class Page {
  constructor(public path: string) {}
  describe(): string {
    return `page ${this.path}`;
  }
}
class LoginPage extends Page {
  constructor() {
    super('/login');
  }
  override describe(): string {
    return `${super.describe()} (login form)`;
  }
}
console.log(new LoginPage().describe());

Output

page /login (login form)

Explanation: override tells the compiler you mean to replace a base method; it errors if the base method does not exist.

13. protected membersIntermediate

Share a helper with subclasses but hide it from outside code.

Show solution
class BasePage {
  protected baseURL = 'https://example.com';
  protected url(path: string): string {
    return this.baseURL + path;
  }
}
class CartPage extends BasePage {
  open(): string {
    return `goto ${this.url('/cart')}`;
  }
}
const cart = new CartPage();
console.log(cart.open());
// @ts-expect-error: Property 'url' is protected and only accessible within class 'BasePage' and its subclasses
const bad = () => cart.url('/x');
console.log(typeof bad);

Output

goto https://example.com/cart
function

Explanation: protected sits between private and public: subclasses can use it, outside code cannot.

14. Abstract classIntermediate

Define an abstract Shape with an abstract area method.

Show solution
abstract class Shape {
  abstract area(): number;
  describe(): string {
    return `${this.constructor.name} area ${this.area().toFixed(2)}`;
  }
}
class Circle extends Shape {
  constructor(private r: number) {
    super();
  }
  area(): number {
    return Math.PI * this.r ** 2;
  }
}
console.log(new Circle(2).describe());

Output

Circle area 12.57

Explanation: an abstract class cannot be created directly. Subclasses must implement every abstract member.

15. Abstract class cannot be instantiatedIntermediate

Show the error from new on an abstract class.

Show solution
abstract class Reporter {
  abstract report(): string;
}
class ConsoleReporter extends Reporter {
  report(): string {
    return 'printed to console';
  }
}
console.log(new ConsoleReporter().report());
// @ts-expect-error: Cannot create an instance of an abstract class
const make = () => new Reporter();
console.log(typeof make);

Output

printed to console
function

Explanation: the compiler blocks new on abstract classes because they are incomplete by design.

16. Implement an interfaceIntermediate

Make a class satisfy an interface contract.

Show solution
interface Clickable {
  click(): string;
}
class Button implements Clickable {
  constructor(private label: string) {}
  click(): string {
    return `clicked "${this.label}"`;
  }
}
const items: Clickable[] = [new Button('Save'), new Button('Cancel')];
items.forEach(i => console.log(i.click()));

Output

clicked "Save"
clicked "Cancel"

Explanation: implements checks the class against the interface, and the array can then hold anything clickable.

17. ES private fields with #Intermediate

Use a # private field that is hidden at runtime too.

Show solution
class Token {
  #value: string;
  constructor(value: string) {
    this.#value = value;
  }
  masked(): string {
    return this.#value.slice(0, 3) + '***';
  }
}
const t = new Token('abc123xyz');
console.log(t.masked(), Object.keys(t).length);

Output

abc*** 0

Explanation: #value is truly private in JavaScript, so it does not appear in Object.keys or JSON, unlike TypeScript’s private.

18. Method chaining with thisIntermediate

Return this from methods so calls can be chained.

Show solution
class QueryBuilder {
  private parts: string[] = [];
  where(cond: string): this {
    this.parts.push(cond);
    return this;
  }
  build(): string {
    return 'WHERE ' + this.parts.join(' AND ');
  }
}
console.log(new QueryBuilder().where('active = 1').where("role = 'qa'").build());

Output

WHERE active = 1 AND role = 'qa'

Explanation: a this return type keeps chaining correct even in subclasses.

19. instanceof narrowingIntermediate

Handle different error classes with instanceof.

Show solution
class TimeoutError extends Error {
  constructor(public ms: number) {
    super(`timed out after ${ms}ms`);
    this.name = 'TimeoutError';
  }
}
function explain(e: unknown): string {
  if (e instanceof TimeoutError) return `retry later (${e.ms}ms)`;
  if (e instanceof Error) return `error: ${e.message}`;
  return 'unknown problem';
}
console.log(explain(new TimeoutError(5000)));
console.log(explain(new Error('boom')));
console.log(explain('oops'));

Output

retry later (5000ms)
error: boom
unknown problem

Explanation: instanceof narrows to the class type, so e.ms is available only in the first branch.

20. Static readonly constantsIntermediate

Keep shared constants on the class.

Show solution
class HttpStatus {
  static readonly OK = 200;
  static readonly NOT_FOUND = 404;
  static isSuccess(code: number): boolean {
    return code >= 200 && code < 300;
  }
}
console.log(HttpStatus.OK, HttpStatus.isSuccess(HttpStatus.NOT_FOUND));

Output

200 false

Explanation: static readonly gives named constants that cannot be changed and live next to related helpers.

21. Class as a typeIntermediate

Use a class name as a type for function parameters.

Show solution
class Point {
  constructor(public x: number, public y: number) {}
}
function distance(a: Point, b: Point): number {
  return Math.hypot(b.x - a.x, b.y - a.y);
}
console.log(distance(new Point(0, 0), new Point(3, 4)));
console.log(distance({ x: 1, y: 1 }, { x: 4, y: 5 }));

Output

5
5

Explanation: a class also defines a type. TypeScript compares shapes, so a plain object with x and y is accepted too.

TypeScript Real-World QA Scenario Programs

22. Page object classReal-world

Write a small page object with a fake page.

Show solution
interface FakePage {
  goto(url: string): Promise<void>;
  fill(sel: string, value: string): Promise<void>;
  click(sel: string): Promise<void>;
}
const log: string[] = [];
const page: FakePage = {
  goto: async url => { log.push(`goto ${url}`); },
  fill: async (sel, value) => { log.push(`fill ${sel}=${value}`); },
  click: async sel => { log.push(`click ${sel}`); },
};
class LoginPage {
  constructor(private readonly page: FakePage) {}
  async login(user: string, pass: string): Promise<void> {
    await this.page.goto('/login');
    await this.page.fill('#user', user);
    await this.page.fill('#pass', pass);
    await this.page.click('button[type=submit]');
  }
}
await new LoginPage(page).login('qa', 'secret');
log.forEach(l => console.log(l));

Output

goto /login
fill #user=qa
fill #pass=secret
click button[type=submit]

Explanation: the page object hides selectors behind a readable method. Passing the page in the constructor makes it easy to fake in tests.

23. Singleton configReal-world

Make a config class with a single shared instance.

Show solution
class Config {
  private static instance?: Config;
  private constructor(public readonly env: string) {}
  static get(): Config {
    return (Config.instance ??= new Config('staging'));
  }
}
const a = Config.get();
const b = Config.get();
console.log(a === b, a.env);
// @ts-expect-error: Constructor of class 'Config' is private and only accessible within the class declaration
const direct = () => new Config('prod');
console.log(typeof direct);

Output

true staging
function

Explanation: a private constructor forces callers through Config.get(), which always returns the same object.

24. Builder pattern for test dataReal-world

Build a user step by step with sensible defaults.

Show solution
type UserData = { name: string; email: string; role: 'admin' | 'viewer'; active: boolean };
class UserBuilder {
  private data: UserData = { name: 'Test User', email: 'user@test.io', role: 'viewer', active: true };
  withName(name: string): this { this.data.name = name; return this; }
  admin(): this { this.data.role = 'admin'; return this; }
  inactive(): this { this.data.active = false; return this; }
  build(): UserData { return { ...this.data }; }
}
const u = new UserBuilder().withName('Ana').admin().build();
console.log(u.name, u.role, u.active);
console.log(new UserBuilder().inactive().build().active);

Output

Ana admin true
false

Explanation: builders keep test data readable: you only state what matters for the test and defaults cover the rest.

25. Custom error hierarchyReal-world

Create an assertion error class that carries expected and actual values.

Show solution
class AssertionError extends Error {
  constructor(public expected: unknown, public actual: unknown) {
    super(`expected ${JSON.stringify(expected)} but got ${JSON.stringify(actual)}`);
    this.name = 'AssertionError';
  }
}
function expectEqual<T>(actual: T, expected: T): void {
  if (actual !== expected) throw new AssertionError(expected, actual);
}
try {
  expectEqual(2 + 2, 4);
  expectEqual('Home', 'Dashboard');
} catch (e) {
  if (e instanceof AssertionError) console.log(`${e.name}: ${e.message}`);
}

Output

AssertionError: expected "Dashboard" but got "Home"

Explanation: a subclass of Error can carry extra fields, and instanceof lets handlers pick it out.

26. Stack class with private storageReal-world

Implement a typed stack of strings.

Show solution
class StringStack {
  private items: string[] = [];
  push(item: string): void { this.items.push(item); }
  pop(): string | undefined { return this.items.pop(); }
  peek(): string | undefined { return this.items[this.items.length - 1]; }
  get size(): number { return this.items.length; }
}
const history = new StringStack();
['/home', '/search', '/cart'].forEach(p => history.push(p));
console.log(history.pop(), history.peek(), history.size);

Output

/cart /search 2

Explanation: keeping the array private means callers can only change it through the class methods.

27. Event emitter classReal-world

Write a tiny event emitter with typed listeners.

Show solution
type Listener = (payload: string) => void;
class Emitter {
  private listeners = new Map<string, Listener[]>();
  on(event: string, fn: Listener): void {
    this.listeners.set(event, [...(this.listeners.get(event) ?? []), fn]);
  }
  emit(event: string, payload: string): number {
    const fns = this.listeners.get(event) ?? [];
    fns.forEach(fn => fn(payload));
    return fns.length;
  }
}
const bus = new Emitter();
bus.on('testEnd', name => console.log(`finished ${name}`));
bus.on('testEnd', name => console.log(`report ${name}`));
console.log(bus.emit('testEnd', 'login'), bus.emit('unknown', 'x'));

Output

finished login
report login
2 0

Explanation: a private Map of listeners keeps state inside the class, and the listener type is checked on every on call.

28. Accessor with lazy loadingReal-world

Load a value the first time a getter is read and cache it.

Show solution
class TestData {
  private cache?: string[];
  loads = 0;
  get users(): string[] {
    if (!this.cache) {
      this.loads++;
      this.cache = ['ana', 'ben', 'cai'];
    }
    return this.cache;
  }
}
const d = new TestData();
console.log(d.users.length, d.users[0], d.loads);

Output

3 ana 1

Explanation: the getter only does the work once, and the optional private field records whether it has run.

29. Retry helper classReal-world

Write a class that retries an async action with a limit.

Show solution
class Retrier {
  constructor(private readonly attempts: number) {}
  async run<T>(action: (attempt: number) => Promise<T>): Promise<T> {
    let lastError: unknown;
    for (let i = 1; i <= this.attempts; i++) {
      try {
        return await action(i);
      } catch (e) {
        lastError = e;
        console.log(`attempt ${i} failed`);
      }
    }
    throw lastError;
  }
}
const result = await new Retrier(3).run(async n => {
  if (n < 3) throw new Error('flaky');
  return 'passed';
});
console.log(result);

Output

attempt 1 failed
attempt 2 failed
passed

Explanation: a generic method keeps the action’s result type, so result is a string here.

30. Accessor-based counter with limitsReal-world

Count clicks but never go above a maximum.

Show solution
class ClickCounter {
  #count = 0;
  constructor(readonly max: number) {}
  click(): this {
    this.#count = Math.min(this.#count + 1, this.max);
    return this;
  }
  get count(): number {
    return this.#count;
  }
}
const c = new ClickCounter(3);
c.click().click().click().click();
console.log(`${c.count}/${c.max}`);

Output

3/3

Explanation: a private field with a getter but no setter makes the value read-only from outside.

Keep Practising

TypeScript Interfaces Practice Programs with Solutions (30 Programs)

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

How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with npx tsx program.ts (or compile it with npx tsc).

New to this topic? Read the TypeScript Interfaces lesson first.

TypeScript Beginner Programs

1. Declare an interfaceBeginner

Describe a user with an interface and create one.

Show solution
interface User {
  id: number;
  email: string;
}
const user: User = { id: 1, email: 'qa@test.io' };
console.log(`#${user.id} ${user.email}`);

Output

#1 qa@test.io

Explanation: an interface names an object shape. Any value annotated with it must have those properties with those types.

2. Interface catches wrong typesBeginner

Show that a string id is rejected by a numeric interface field.

Show solution
interface TestCase {
  id: number;
  title: string;
}
const good: TestCase = { id: 7, title: 'login' };
// @ts-expect-error: Type 'string' is not assignable to type 'number'
const bad: TestCase = { id: '7', title: 'login' };
console.log(good.id, bad.title);

Output

7 login

Explanation: each field is checked against the interface, so a mismatched type fails to compile.

3. Optional membersBeginner

Add an optional tags field and print it only when present.

Show solution
interface Spec {
  title: string;
  tags?: string[];
}
const specs: Spec[] = [{ title: 'login', tags: ['smoke'] }, { title: 'search' }];
for (const s of specs) console.log(`${s.title}${s.tags ? ' [' + s.tags.join(',') + ']' : ''}`);

Output

login [smoke]
search

Explanation: tags? may be missing, so its type is string[] | undefined and you check it before use.

4. Readonly membersBeginner

Make an interface field readonly.

Show solution
interface Build {
  readonly number: number;
  status: string;
}
const build: Build = { number: 512, status: 'running' };
build.status = 'passed';
// @ts-expect-error: Cannot assign to 'number' because it is a read-only property
const bump = () => (build.number = 513);
console.log(build.number, build.status, typeof bump);

Output

512 passed function

Explanation: readonly lets you set the value once when the object is created and blocks later changes.

5. Interface as a function parameterBeginner

Write a function that accepts any object matching an interface.

Show solution
interface Credentials {
  username: string;
  password: string;
}
function maskedLogin(c: Credentials): string {
  return `${c.username} / ${'*'.repeat(c.password.length)}`;
}
console.log(maskedLogin({ username: 'admin', password: 'secret' }));

Output

admin / ******

Explanation: the parameter type documents what the function needs, and every call is checked.

6. Methods in an interfaceBeginner

Describe a logger with methods and implement it as an object.

Show solution
interface Logger {
  info(msg: string): void;
  error(msg: string): void;
}
const logger: Logger = {
  info: msg => console.log(`INFO  ${msg}`),
  error: msg => console.log(`ERROR ${msg}`),
};
logger.info('suite started');
logger.error('login failed');

Output

INFO  suite started
ERROR login failed

Explanation: method signatures type the parameters, so msg is a string in the implementation without repeating the annotation.

7. Function type in an interfaceBeginner

Describe a validator as a callable interface.

Show solution
interface Validator {
  (value: string): boolean;
}
const isEmail: Validator = v => /^[^@\s]+@[^@\s]+\.[a-z]+$/i.test(v);
console.log(isEmail('qa@test.io'), isEmail('qa-at-test'));

Output

true false

Explanation: a call signature in an interface describes a function. A type Validator = (value: string) =&gt; boolean alias would do the same.

8. Array of interface objectsBeginner

Total the price of items in a cart.

Show solution
interface CartItem {
  name: string;
  price: number;
  qty: number;
}
const cart: CartItem[] = [
  { name: 'pen', price: 1.5, qty: 4 },
  { name: 'book', price: 12, qty: 1 },
];
const total = cart.reduce((sum, i) => sum + i.price * i.qty, 0);
console.log(`total $${total.toFixed(2)}`);

Output

total $18.00

Explanation: the element type gives the reduce callback typed access to price and qty.

9. Nested interfacesBeginner

Use one interface inside another.

Show solution
interface Address {
  city: string;
  zip: string;
}
interface Customer {
  name: string;
  address: Address;
}
const c: Customer = { name: 'Ana', address: { city: 'Pune', zip: '411001' } };
console.log(`${c.name}, ${c.address.city} ${c.address.zip}`);

Output

Ana, Pune 411001

Explanation: small interfaces can be combined, so the same Address can be reused in orders, invoices and profiles.

10. Index signature in an interfaceBeginner

Describe a map of environment URLs.

Show solution
interface EnvUrls {
  [env: string]: string;
}
const urls: EnvUrls = { dev: 'http://localhost:3000', staging: 'https://staging.example.com' };
urls.prod = 'https://example.com';
console.log(Object.keys(urls).join(', '));

Output

dev, staging, prod

Explanation: the index signature allows any string key, as long as every value is a string.

TypeScript Intermediate Programs

11. Extend an interfaceIntermediate

Build Admin on top of User with extends.

Show solution
interface User {
  id: number;
  email: string;
}
interface Admin extends User {
  permissions: string[];
}
const admin: Admin = { id: 1, email: 'root@test.io', permissions: ['read', 'write', 'delete'] };
console.log(`${admin.email} can ${admin.permissions.join('/')}`);

Output

root@test.io can read/write/delete

Explanation: extends copies the base members, so Admin needs id, email and permissions.

12. Extend multiple interfacesIntermediate

Combine Timestamps and Identifiable into one interface.

Show solution
interface Identifiable {
  id: string;
}
interface Timestamps {
  createdAt: Date;
}
interface Ticket extends Identifiable, Timestamps {
  title: string;
}
const t: Ticket = { id: 'BUG-12', createdAt: new Date('2026-01-15T00:00:00Z'), title: 'Login button misaligned' };
console.log(`${t.id} (${t.createdAt.toISOString().slice(0, 10)}): ${t.title}`);

Output

BUG-12 (2026-01-15): Login button misaligned

Explanation: an interface can extend several others at once, a clean way to share common fields.

13. Class implements an interfaceIntermediate

Make a class promise to follow an interface.

Show solution
interface Shape {
  area(): number;
}
class Rect implements Shape {
  constructor(private w: number, private h: number) {}
  area(): number {
    return this.w * this.h;
  }
}
const shapes: Shape[] = [new Rect(2, 3), new Rect(4, 5)];
console.log(shapes.map(s => s.area()).join(', '));

Output

6, 20

Explanation: implements makes the compiler check that the class has every member of the interface.

14. Missing member in implementsIntermediate

Show the error when a class forgets an interface method.

Show solution
interface Page {
  open(): string;
  title(): string;
}
// @ts-expect-error: Class 'HomePage' incorrectly implements interface 'Page'
class HomePage implements Page {
  open(): string {
    return 'opened /';
  }
}
console.log(new HomePage().open());

Output

opened /

Explanation: the class compiles only when it has both open and title. This keeps every page object consistent.

15. Interface vs type aliasIntermediate

Describe the same shape with an interface and a type alias and use both.

Show solution
interface PointI {
  x: number;
  y: number;
}
type PointT = { x: number; y: number };
const a: PointI = { x: 1, y: 2 };
const b: PointT = a;
console.log(b.x + b.y);

Output

3

Explanation: for object shapes the two are interchangeable. Interfaces can be extended and merged; type aliases can also name unions and tuples.

16. Union types need a type aliasIntermediate

Model a status that is one of three strings and use it inside an interface.

Show solution
type Status = 'passed' | 'failed' | 'skipped';
interface Result {
  name: string;
  status: Status;
}
const results: Result[] = [
  { name: 'login', status: 'passed' },
  { name: 'cart', status: 'failed' },
];
console.log(results.filter(r => r.status === 'failed').map(r => r.name).join(', '));

Output

cart

Explanation: an interface cannot describe a union of literals, so a type alias holds the union and the interface uses it.

17. Declaration mergingIntermediate

Declare the same interface twice and see the members combine.

Show solution
interface Settings {
  theme: string;
}
interface Settings {
  fontSize: number;
}
const s: Settings = { theme: 'dark', fontSize: 14 };
console.log(`${s.theme} ${s.fontSize}px`);

Output

dark 14px

Explanation: interfaces with the same name merge. This is how libraries let you add fields to their types, for example Playwright fixtures.

18. Generic interfaceIntermediate

Write an ApiResponse&lt;T&gt; interface and use it with two data types.

Show solution
interface ApiResponse<T> {
  status: number;
  data: T;
}
const user: ApiResponse<{ name: string }> = { status: 200, data: { name: 'Ana' } };
const ids: ApiResponse<number[]> = { status: 200, data: [1, 2, 3] };
console.log(user.data.name, ids.data.length);

Output

Ana 3

Explanation: the type parameter lets one interface describe responses with any payload while still typing data.

19. Interface for constructor optionsIntermediate

Use an interface with optional fields as constructor options.

Show solution
interface BrowserOptions {
  headless?: boolean;
  slowMo?: number;
}
class FakeBrowser {
  readonly headless: boolean;
  readonly slowMo: number;
  constructor(opts: BrowserOptions = {}) {
    this.headless = opts.headless ?? true;
    this.slowMo = opts.slowMo ?? 0;
  }
}
const b1 = new FakeBrowser();
const b2 = new FakeBrowser({ headless: false, slowMo: 50 });
console.log(b1.headless, b1.slowMo, b2.headless, b2.slowMo);

Output

true 0 false 50

Explanation: an options interface keeps the constructor flexible, and defaults fill in what callers leave out.

20. Readonly arrays in an interfaceIntermediate

Protect a list inside an interface from being changed.

Show solution
interface Suite {
  name: string;
  readonly tests: readonly string[];
}
const suite: Suite = { name: 'auth', tests: ['login', 'logout'] };
// @ts-expect-error: Property 'push' does not exist on type 'readonly string[]'
const add = () => suite.tests.push('reset');
console.log(suite.tests.join(', '), typeof add);

Output

login, logout function

Explanation: readonly on the property stops reassignment, and readonly string[] stops changes to the array itself.

TypeScript Real-World QA Scenario Programs

21. Interface for a page objectReal-world

Describe a login page with an interface and give it a fake implementation.

Show solution
interface LoginPage {
  goto(): Promise<void>;
  login(user: string, pass: string): Promise<string>;
}
const fakeLogin: LoginPage = {
  async goto() {
    console.log('navigate /login');
  },
  async login(user, pass) {
    return pass === 'secret' ? `welcome ${user}` : 'invalid credentials';
  },
};
await fakeLogin.goto();
console.log(await fakeLogin.login('qa', 'secret'));
console.log(await fakeLogin.login('qa', 'wrong'));

Output

navigate /login
welcome qa
invalid credentials

Explanation: coding against an interface lets you swap a real Playwright page object for a fake in unit tests.

22. Discriminated union of interfacesReal-world

Handle three kinds of test events with a kind field.

Show solution
interface StartEvent { kind: 'start'; test: string }
interface PassEvent { kind: 'pass'; test: string; ms: number }
interface FailEvent { kind: 'fail'; test: string; error: string }
type TestEvent = StartEvent | PassEvent | FailEvent;
function format(e: TestEvent): string {
  switch (e.kind) {
    case 'start': return `> ${e.test}`;
    case 'pass': return `ok ${e.test} (${e.ms}ms)`;
    case 'fail': return `x ${e.test}: ${e.error}`;
  }
}
const events: TestEvent[] = [
  { kind: 'start', test: 'login' },
  { kind: 'pass', test: 'login', ms: 840 },
  { kind: 'fail', test: 'cart', error: 'timeout' },
];
events.forEach(e => console.log(format(e)));

Output

> login
ok login (840ms)
x cart: timeout

Explanation: the kind literal narrows the union in each case, so ms and error are only used where they exist.

23. Type guard for an interfaceReal-world

Check unknown JSON at runtime before treating it as a User.

Show solution
interface User {
  id: number;
  email: string;
}
function isUser(x: unknown): x is User {
  return typeof x === 'object' && x !== null
    && typeof (x as User).id === 'number' && typeof (x as User).email === 'string';
}
const inputs: unknown[] = [JSON.parse('{"id":1,"email":"a@test.io"}'), JSON.parse('{"id":"2"}')];
for (const i of inputs) console.log(isUser(i) ? `valid: ${i.email}` : 'invalid payload');

Output

valid: a@test.io
invalid payload

Explanation: interfaces disappear at runtime, so data from an API must be checked. The x is User guard narrows the type after the check.

24. Interface with a generic constraintReal-world

Write a function that sorts anything with a priority field.

Show solution
interface HasPriority {
  priority: number;
}
function byPriority<T extends HasPriority>(items: T[]): T[] {
  return [...items].sort((a, b) => a.priority - b.priority);
}
const bugs = [
  { id: 'B-3', priority: 2 },
  { id: 'B-1', priority: 1 },
  { id: 'B-9', priority: 3 },
];
console.log(byPriority(bugs).map(b => b.id).join(' > '));

Output

B-1 > B-3 > B-9

Explanation: T extends HasPriority requires the field but keeps the full item type, so b.id is still available in the result.

25. Callable and property members togetherReal-world

Describe a counter function that also exposes a count property.

Show solution
interface Counter {
  (): number;
  count: number;
  reset(): void;
}
function makeCounter(): Counter {
  const c = (() => ++c.count) as Counter;
  c.count = 0;
  c.reset = () => { c.count = 0; };
  return c;
}
const next = makeCounter();
next(); next();
console.log(next(), next.count);
next.reset();
console.log(next.count);

Output

3 3
0

Explanation: an interface can mix a call signature with properties, which describes functions that carry state.

26. Extending a generic interfaceReal-world

Build a paginated response on top of a generic base response.

Show solution
interface ApiResponse<T> {
  status: number;
  data: T;
}
interface Paged<T> extends ApiResponse<T[]> {
  page: number;
  totalPages: number;
}
const page2: Paged<string> = { status: 200, data: ['c', 'd'], page: 2, totalPages: 3 };
const hasMore = page2.page < page2.totalPages;
console.log(`${page2.data.join(',')} | page ${page2.page}/${page2.totalPages} | more: ${hasMore}`);

Output

c,d | page 2/3 | more: true

Explanation: a generic interface can extend another generic one and fix part of its type, here data becomes T[].

27. Repository interface with a fakeReal-world

Define a data repository interface and an in-memory implementation.

Show solution
interface Repo<T extends { id: number }> {
  add(item: T): void;
  get(id: number): T | undefined;
  all(): T[];
}
class MemoryRepo<T extends { id: number }> implements Repo<T> {
  private items = new Map<number, T>();
  add(item: T): void { this.items.set(item.id, item); }
  get(id: number): T | undefined { return this.items.get(id); }
  all(): T[] { return [...this.items.values()]; }
}
const users = new MemoryRepo<{ id: number; name: string }>();
users.add({ id: 1, name: 'Ana' });
users.add({ id: 2, name: 'Ben' });
console.log(users.get(2)?.name, users.get(3)?.name ?? 'missing', users.all().length);

Output

Ben missing 2

Explanation: tests can depend on Repo&lt;T&gt; and use the memory version, while production code uses a database version with the same interface.

28. Optional methodsReal-world

Call a hook only if the plugin defines it.

Show solution
interface Plugin {
  name: string;
  beforeAll?(): string;
  afterAll?(): string;
}
const plugins: Plugin[] = [
  { name: 'screenshots', afterAll: () => 'saved 3 screenshots' },
  { name: 'auth', beforeAll: () => 'logged in' },
];
for (const p of plugins) console.log(`${p.name}: ${p.beforeAll?.() ?? '-'} | ${p.afterAll?.() ?? '-'}`);

Output

screenshots: - | saved 3 screenshots
auth: logged in | -

Explanation: optional methods may be missing, so ?.() calls them only when they exist.

29. Mapped type over an interfaceReal-world

Turn every field of an interface into a validation message slot.

Show solution
interface SignupForm {
  email: string;
  password: string;
  age: number;
}
type FormErrors = { [K in keyof SignupForm]?: string };
function validate(f: SignupForm): FormErrors {
  const errors: FormErrors = {};
  if (!f.email.includes('@')) errors.email = 'invalid email';
  if (f.password.length < 8) errors.password = 'too short';
  if (f.age < 18) errors.age = 'must be 18+';
  return errors;
}
console.log(JSON.stringify(validate({ email: 'qa', password: 'secret', age: 30 })));

Output

{"email":"invalid email","password":"too short"}

Explanation: the mapped type reuses the interface keys, so adding a form field automatically allows an error for it.

30. Fixture types like PlaywrightReal-world

Model test fixtures with an interface and use them in a fake test runner.

Show solution
interface Fixtures {
  baseURL: string;
  user: { email: string };
}
type TestFn = (f: Fixtures) => string;
function runTest(name: string, fn: TestFn): void {
  const fixtures: Fixtures = { baseURL: 'https://example.com', user: { email: 'qa@test.io' } };
  console.log(`${name}: ${fn(fixtures)}`);
}
runTest('profile', ({ baseURL, user }) => `${baseURL}/profile as ${user.email}`);

Output

profile: https://example.com/profile as qa@test.io

Explanation: Playwright’s test.extend&lt;Fixtures&gt;() works the same way: an interface describes the fixtures, and test callbacks get them fully typed.

Keep Practising