Create a GitHub Account and Set Up SSH Keys (Windows, macOS, Linux)

In this lesson you will create a professional GitHub account, secure it with two-factor authentication, and connect your computer to GitHub with SSH keys, so you can push and pull without typing credentials.

๐Ÿ“– What You’ll Learn: creating and completing a GitHub profile, two-factor authentication, HTTPS vs SSH, generating an ed25519 SSH key, the SSH agent on every operating system, adding the key to GitHub, testing the connection and fixing common SSH errors.


๐Ÿ‘ค Step 1: Create Your GitHub Account

  1. Go to github.com and click Sign up.
  2. Enter your email, a strong password and a username.
  3. Verify your email address with the code GitHub sends you.
  4. Choose the Free plan. It includes unlimited public and private repositories.

๐Ÿ’ก Tip: Choose your username carefully: it appears in your profile URL (github.com/your-username) and in every repository link you share with recruiters. Something like asha-verma-qa looks more professional than coolcoder99.

Complete your profile

  • Add a photo, your name, a short bio (for example “QA Automation Engineer | Playwright | TypeScript”) and your location.
  • Later, create a profile README by making a public repository with the same name as your username; its README appears on your profile page.

๐Ÿ›ก๏ธ Step 2: Turn On Two-Factor Authentication (2FA)

GitHub requires two-factor authentication for accounts that contribute code. Set it up early:

  1. Open Settings, Password and authentication.
  2. Enable 2FA with an authenticator app (Google Authenticator, Microsoft Authenticator, Authy) or a passkey.
  3. Download and store your recovery codes in a safe place. They are the only way back in if you lose your phone.

๐Ÿ” HTTPS or SSH? How Git Talks to GitHub

When you push or pull, Git must prove who you are. There are two connection types:

HTTPSSSH
Remote URLhttps://github.com/user/repo.gitgit@github.com:user/repo.git
AuthenticationGit Credential Manager (browser sign-in) or a personal access tokenAn SSH key pair on your computer
Setup effortVery low on Windows and macOSOne-time key setup
Works through strict firewallsUsuallySometimes blocked (port 22)
Popular withBeginners, Windows usersDevelopers, Linux users, CI servers

Both are secure. Many developers use SSH so they never type credentials again. The rest of this lesson sets up SSH.


๐Ÿ—๏ธ Step 3: Check for Existing SSH Keys

Open Git Bash (Windows) or a terminal (macOS, Linux):

ls -al ~/.ssh

If you see id_ed25519 and id_ed25519.pub, you already have a key and can skip to Step 5.


๐Ÿ”‘ Step 4: Generate a New SSH Key

ssh-keygen -t ed25519 -C "asha.verma@example.com"
  • Press Enter to accept the default file location (~/.ssh/id_ed25519).
  • Enter a passphrase (recommended) and confirm it.

This creates two files:

FileWhat it isShare it?
~/.ssh/id_ed25519Private keyNever. It stays on your computer
~/.ssh/id_ed25519.pubPublic keyYes, you add it to GitHub

๐Ÿค– Step 5: Add the Key to the SSH Agent

The SSH agent remembers your passphrase so you do not type it on every push.

macOS and Linux

eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519

On macOS you can store the passphrase in the Keychain with ssh-add --apple-use-keychain ~/.ssh/id_ed25519.

Windows (PowerShell as Administrator)

Get-Service -Name ssh-agent | Set-Service -StartupType Manual
Start-Service ssh-agent
ssh-add $env:USERPROFILE\.ssh\id_ed25519

โ˜๏ธ Step 6: Add the Public Key to GitHub

  1. Copy the public key:
# Windows (Git Bash)
clip < ~/.ssh/id_ed25519.pub

# macOS
pbcopy < ~/.ssh/id_ed25519.pub

# Linux: print it and copy from the terminal
cat ~/.ssh/id_ed25519.pub
  1. On GitHub, open Settings, SSH and GPG keys, New SSH key.
  2. Title: something like “Work laptop”. Key type: Authentication Key. Paste the key and click Add SSH key.

โœ… Step 7: Test the Connection

ssh -T git@github.com

The first time, type yes to trust GitHub’s host fingerprint. Success looks like:

Hi asha-verma-qa! You've successfully authenticated, but GitHub does not provide shell access.

You can now clone with SSH URLs:

git clone git@github.com:your-username/your-repo.git

Switch an existing repository from HTTPS to SSH:

git remote set-url origin git@github.com:your-username/your-repo.git

Remotes are explained in Remote repositories.


๐Ÿž Troubleshooting

ErrorCause and fix
Permission denied (publickey)Key not added to the agent or GitHub. Run ssh-add -l to list loaded keys and check GitHub Settings, SSH keys
Could not open a connection to your authentication agentStart the agent: eval "$(ssh-agent -s)" (or Start-Service on Windows)
Connection timed out on port 22Firewall blocks SSH. Use HTTPS, or SSH over port 443 with host ssh.github.com
Host key verification failedRemove the old entry with ssh-keygen -R github.com and connect again

๐Ÿ“ Assignment

  1. Create a GitHub account with a professional username and complete your profile.
  2. Enable two-factor authentication and store your recovery codes safely.
  3. Generate an ed25519 SSH key with a passphrase and add it to the SSH agent.
  4. Add the public key to GitHub and confirm with ssh -T git@github.com.
  5. Create an empty public repository called git-practice on GitHub; you will use it in Module 3.

โ“ FAQ

๐Ÿค” How do I set up an SSH key for GitHub?

Run ssh-keygen -t ed25519 -C "your-email", add the key to the SSH agent with ssh-add, copy the .pub file into GitHub Settings, SSH and GPG keys, then test with ssh -T git@github.com.

๐Ÿค” Should I use HTTPS or SSH with GitHub?

Both are secure. HTTPS with Git Credential Manager is easiest for beginners on Windows and macOS. SSH avoids credential prompts and is common on Linux and CI servers.

๐Ÿค” Can I use my GitHub password to push code?

No. GitHub requires Git Credential Manager, an SSH key or a personal access token for Git operations.

๐Ÿค” Is it safe to share my SSH public key?

Yes. The .pub file is meant to be shared. Never share the private key file without the .pub extension.

๐Ÿค” Can I use the same SSH key on several computers?

It is better to create one key per computer. If a laptop is lost, you delete only that key from GitHub.


๐ŸŽฏ Next Steps

๐ŸŽฌ Learn Git and GitHub step by step: watch the series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Configure Git: Name, Email, Editor, Default Branch and Aliases

Before your first commit, Git needs to know who you are and how you like to work. In this lesson you will configure Git once, the right way: identity, editor, default branch, line endings, useful defaults and time-saving aliases.

๐Ÿ“– What You’ll Learn: the system, global and local config levels, setting name and email, choosing an editor, the default branch name, line endings with core.autocrlf, useful extras, aliases, viewing and editing config, and credentials for GitHub.


๐Ÿชช Why Configure Git?

Every commit records who made it. Before your first commit, Git needs your name and email. A few more settings make Git friendlier: your favourite editor, the default branch name and how line endings are handled. You set these once per computer.


๐Ÿงฉ The Three Configuration Levels

LevelOptionApplies toStored in
System--systemEvery user on the computerGit’s installation folder
Global--globalAll repositories of your user account~/.gitconfig
Local--local (default inside a repo)One repository only.git/config in that repo

The most specific level wins: local overrides global, global overrides system. Most of the time you use --global.


๐Ÿ‘ค Step 1: Set Your Name and Email

git config --global user.name "Asha Verma"
git config --global user.email "asha.verma@example.com"

๐Ÿ’ก Tip: Use the same email as your GitHub account (or GitHub’s private no-reply address, shown in GitHub Settings, Emails). That links your commits to your GitHub profile and contribution graph.

Need a different email for work repositories? Set it locally inside that repository:

cd path/to/work-repo
git config user.email "asha.verma@company.com"

๐Ÿ“ Step 2: Choose Your Editor

Git opens an editor for commit messages, merges and interactive rebases. Set VS Code:

git config --global core.editor "code --wait"

--wait tells Git to wait until you close the editor tab. Other options: "notepad" on Windows, "nano" on Linux and macOS.


๐ŸŒฟ Step 3: Default Branch Name

New repositories should start with main, matching GitHub:

git config --global init.defaultBranch main

โ†ฉ๏ธ Step 4: Line Endings

Windows and macOS/Linux use different line-ending characters, which can make every line look “changed” in a diff. Configure Git to normalize them:

# Windows
git config --global core.autocrlf true

# macOS and Linux
git config --global core.autocrlf input

For teams, a .gitattributes file in the repository (for example * text=auto) makes this consistent regardless of each person’s settings.


โš™๏ธ Step 5: Useful Extras

git config --global pull.rebase false         # git pull merges (default behaviour, avoids a warning)
git config --global push.autoSetupRemote true # first push of a new branch sets its upstream automatically
git config --global color.ui auto             # coloured output (usually already on)
git config --global fetch.prune true          # remove deleted remote branches on fetch

The pull and push options are explained in fetch vs pull and clone, push and pull.


โŒจ๏ธ Step 6: Aliases (Shortcuts)

Save typing with aliases:

git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.cm "commit -m"
git config --global alias.lg "log --oneline --graph --decorate --all"

Now git st runs git status and git lg shows a compact history graph.


๐Ÿ” View and Edit Your Configuration

git config --list                     # all settings
git config --list --show-origin       # settings and the file each comes from
git config user.email                 # one setting
git config --global --edit            # open ~/.gitconfig in your editor
git config --global --unset alias.co  # remove a setting

Your global file looks like this:

[user]
	name = Asha Verma
	email = asha.verma@example.com
[core]
	editor = code --wait
	autocrlf = true
[init]
	defaultBranch = main
[alias]
	st = status
	lg = log --oneline --graph --decorate --all

๐Ÿ” Credentials for GitHub over HTTPS

When you push over HTTPS, Git needs to authenticate with GitHub. Git for Windows and recent macOS setups use Git Credential Manager, which opens the browser once and stores the token securely. On Linux you can install Git Credential Manager or use SSH keys instead, covered in the next lesson.

โš ๏ธ Common mistake: GitHub does not accept your account password for Git operations. Use Git Credential Manager, SSH keys or a personal access token.


๐Ÿ“ Assignment

  1. Set your global name, email, editor (VS Code), default branch (main) and line-ending setting.
  2. Run git config --list --show-origin and find which file each of your settings is stored in.
  3. Create the aliases st and lg, and test them later in your first repository.
  4. In any repository, set a local email and confirm with git config user.email that it overrides the global one.
  5. Open ~/.gitconfig with git config --global --edit and read through it.

โ“ FAQ

๐Ÿค” How do I set my username and email in Git?

Run git config --global user.name "Your Name" and git config --global user.email "you@example.com". Check with git config --list.

๐Ÿค” How do I change the default branch name to main?

git config --global init.defaultBranch main. New repositories created with git init then start on main.

๐Ÿค” Where is the Git config file?

The global file is ~/.gitconfig in your home folder; each repository also has .git/config. Run git config --list --show-origin to see every file in use.

๐Ÿค” How do I set VS Code as the Git editor?

git config --global core.editor "code --wait".

๐Ÿค” What is core.autocrlf?

It controls line-ending conversion. Use true on Windows and input on macOS and Linux to avoid noisy diffs caused by different line endings.


๐ŸŽฏ Next Steps

๐ŸŽฌ Learn Git and GitHub step by step: watch the series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

How to Install Git on Windows and Linux (Step by Step)

Before you can use Git, it has to be installed on your computer. This lesson walks you through installing Git on Windows (with the installer or winget) and on the most popular Linux distributions, with the installer options that matter and fixes for common problems.

๐Ÿ“– What You’ll Learn: checking for an existing Git, the Git for Windows installer and its key options, installing with winget, installing on Ubuntu, Fedora, Arch and others, updating Git, and troubleshooting.


โœ… Before You Start

Check whether Git is already installed. Open a terminal (Command Prompt, PowerShell or Windows Terminal on Windows; Terminal on Linux) and run:

git --version

If you see something like git version 2.47.1, Git is installed; you can still follow this lesson to update it. If you see “command not found” or “‘git’ is not recognized”, install it now.

On a Mac? Follow Install Git on macOS instead, then continue with Configure Git.


๐ŸชŸ Install Git on Windows (Installer)

  1. Go to git-scm.com and click Download for Windows. Choose the 64-bit Git for Windows Setup installer.
  2. Run the installer. Most default options are fine; these are the important screens:
Installer screenRecommended choiceWhy
Choosing the default editorVisual Studio Code (or Notepad++)The default, Vim, is hard for beginners
Adjusting the name of the initial branchOverride… and use “main”GitHub uses main as the default branch name
Adjusting your PATH environmentGit from the command line and also from 3rd-party softwareLets you use git in PowerShell, CMD and VS Code
SSH executableUse bundled OpenSSHWorks with the SSH lesson
Line ending conversionsCheckout Windows-style, commit Unix-styleAvoids line-ending problems with teammates on macOS and Linux
Terminal emulatorUse MinTTYBetter Git Bash terminal
Default behaviour of git pullFast-forward or merge (default)Explained in fetch vs pull
Credential helperGit Credential ManagerSigns in to GitHub securely in the browser
  1. Click Install, then Finish.
  2. Open a new terminal and verify:
git --version

โš ๏ธ Common mistake: If git is still “not recognized”, close every terminal and VS Code window and open them again so they pick up the updated PATH. If it still fails, re-run the installer and check the PATH option above.

What did the installer add?

  • Git Bash: a Linux-style terminal for Windows. Commands in this course such as ls, cat and touch work there. See Essential Terminal Commands for Git.
  • Git GUI: a simple graphical tool (rarely needed).
  • Git Credential Manager: stores your GitHub login securely.

โšก Install Git on Windows with winget

Prefer the command line? Windows 10 and 11 include the winget package manager:

winget install --id Git.Git -e --source winget

Close and reopen the terminal, then run git --version. winget uses the installer defaults, so set the default branch name and editor in the next lesson.


๐Ÿง Install Git on Linux

Use your distribution’s package manager:

# Ubuntu, Debian, Linux Mint
sudo apt update
sudo apt install git

# Fedora
sudo dnf install git

# CentOS Stream, RHEL, Rocky, AlmaLinux
sudo dnf install git

# Arch Linux, Manjaro
sudo pacman -S git

# openSUSE
sudo zypper install git

Verify:

git --version

๐Ÿ“ Note: Distribution packages can be a few versions behind the latest Git release. That is fine for this course. On Ubuntu you can get newer versions from the official Git PPA: sudo add-apt-repository ppa:git-core/ppa, then sudo apt update && sudo apt install git.


๐Ÿ”„ Updating Git Later

PlatformUpdate command
Windows (Git for Windows 2.16.1 or newer)git update-git-for-windows
Windows (winget)winget upgrade --id Git.Git
Ubuntu or Debiansudo apt update && sudo apt install --only-upgrade git
Fedorasudo dnf upgrade git

๐Ÿž Troubleshooting

ProblemFix
'git' is not recognized on WindowsReopen the terminal; re-run the installer with the PATH option “from the command line and also from 3rd-party software”
VS Code does not find GitRestart VS Code; check Settings, git.path
Permission denied on LinuxUse sudo for the install command
Old version on LinuxUse the distribution’s backports or the Git PPA (Ubuntu)
Corporate proxy blocks downloadsAsk IT for the approved installer, or download on another network

๐Ÿ“ Assignment

  1. Install Git on your computer and paste the output of git --version into a notes file.
  2. On Windows, open Git Bash and run pwd, ls and cd ~. What does each command show?
  3. Open VS Code, open any folder, and check that the Source Control panel (Ctrl + Shift + G) no longer says Git is missing.
  4. Write down which line-ending option you chose during installation, and why it matters for teams.

โ“ FAQ

๐Ÿค” How do I install Git on Windows?

Download Git for Windows from git-scm.com, run the installer (choose VS Code as editor, “main” as the default branch and the recommended PATH option), then check git --version in a new terminal. Or run winget install --id Git.Git -e --source winget.

๐Ÿค” How do I install Git on Ubuntu?

Run sudo apt update and sudo apt install git, then verify with git --version.

๐Ÿค” How do I check if Git is installed?

Open a terminal and run git --version. If it prints a version number, Git is installed.

๐Ÿค” What is Git Bash?

A terminal installed with Git for Windows that supports Linux-style commands such as ls, cat and rm, which makes following Git tutorials easier on Windows.

๐Ÿค” Do I need a GitHub account to install Git?

No. Git works without an account. You will create a GitHub account in Lesson 6 to share your repositories online.


๐ŸŽฏ Next Steps

๐ŸŽฌ Learn Git and GitHub step by step: watch the series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

What Is Git and GitHub? Version Control Explained for Beginners

Welcome to Lesson 1 of the free Git and GitHub tutorial. Before typing any commands, you will understand what version control is, what Git and GitHub each do, how they differ, and the key words used throughout the course.

๐Ÿ“– What You’ll Learn: the problem version control solves, what Git is, what GitHub adds, Git vs GitHub, key terms (repository, commit, branch, merge, remote, pull request), the basic workflow, and why Git matters for testers.


๐Ÿ—‚๏ธ The Problem Git Solves

Have you ever had files like these?

test-plan.docx
test-plan-final.docx
test-plan-final-v2.docx
test-plan-final-v2-REALLY-FINAL.docx

That is “version control” done by hand: hard to compare, easy to overwrite, and impossible to share safely with a team. Software projects have the same problem on a much bigger scale: hundreds of files, many people editing them at the same time, and the need to know who changed what, when and why.

Version control software solves this. It records every change to your files as a series of snapshots, lets you go back to any earlier version, and lets several people work on the same project without overwriting each other.


๐Ÿง  What Is Git?

Git is the world’s most widely used version control system. It is free, open source, and runs on your own computer.

  • Created in 2005 by Linus Torvalds, the creator of Linux, to manage the Linux kernel’s source code.
  • Distributed: every developer has a full copy of the project and its complete history, so you can work offline and nothing depends on a single server.
  • Fast: most operations (commit, branch, view history) happen locally in milliseconds.
  • Safe: every snapshot is identified by a cryptographic hash, so history cannot be silently corrupted.

With Git you can:

  • Save snapshots of your project (commits) with a message explaining the change.
  • See exactly what changed between any two versions.
  • Work on new features in isolated branches and merge them when ready.
  • Undo mistakes, even days later.

โ˜๏ธ What Is GitHub?

GitHub is an online platform that hosts Git repositories and adds tools for working together. It launched in 2008 and has been owned by Microsoft since 2018. It is the largest home of open-source code in the world.

GitHub adds what Git alone does not have:

GitHub featureWhat it gives you
Remote repositoriesA shared copy of your project in the cloud
Pull requestsPropose, discuss and review changes before merging
Issues and ProjectsTrack bugs, tasks and plans
GitHub ActionsAutomatically build, test and deploy (CI/CD)
GitHub PagesHost websites for free
Security toolsDependabot alerts, secret scanning, code scanning
ProfilesShow your work to recruiters and the community

โš–๏ธ Git vs GitHub: The Key Difference

GitGitHub
What it isVersion control softwareA website and service that hosts Git repositories
Where it runsOn your computerIn the cloud (github.com)
Needs internetNoYes
Made byLinus Torvalds and the open-source communityGitHub Inc., owned by Microsoft
CostFree and open sourceFree plans, plus paid plans for teams and enterprises
AlternativesMercurial, SVN (older)GitLab, Bitbucket, Azure DevOps Repos

๐Ÿ’ก Tip: An easy way to remember it: Git is the tool, GitHub is the place where you share what the tool tracks. You can use Git without GitHub, but GitHub is built around Git.


๐Ÿ“š Key Words You Will Meet in This Course

TermMeaning
Repository (repo)A project folder tracked by Git, including its full history
CommitA saved snapshot of your changes, with a message and an author
BranchAn independent line of work, e.g. a new feature
MergeCombining the changes from one branch into another
RemoteA copy of the repository on a server, such as GitHub
CloneDownloading a full copy of a remote repository
Push / PullSending your commits to the remote / getting others’ commits
Pull request (PR)A GitHub request to review and merge a branch
HEADA pointer to the commit you are currently on

๐Ÿ”„ How a Typical Workflow Looks

 Your computer                                         GitHub
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”       โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ Working folder โ†’ Staging area โ†’ Local repo โ”‚ push  โ”‚ Remote repo  โ”‚
โ”‚   (edit)         (git add)     (git commit)โ”‚ โ”€โ”€โ”€โ”€โ–ถ โ”‚  (shared)    โ”‚
โ”‚                                            โ”‚ โ—€โ”€โ”€โ”€โ”€ โ”‚              โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ pull  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
  1. You edit files in your working folder.
  2. You choose which changes to save with git add (the staging area).
  3. You save a snapshot with git commit.
  4. You push commits to GitHub so others can see them, and pull their changes.

Each step has its own lesson in Modules 2 and 3.


๐Ÿงช Why Testers and QA Engineers Need Git

  • Automation frameworks, test data and CI pipelines all live in Git repositories.
  • Tests run automatically in GitHub Actions on every pull request (see Run Playwright tests in GitHub Actions).
  • Reviewing developers’ pull requests helps you test earlier.
  • Git and GitHub questions appear in almost every QA automation and SDET interview.

๐Ÿ“ Assignment

  1. In your own words, explain the difference between Git and GitHub to a friend in three sentences.
  2. List three problems in your current work (or studies) that version control would solve.
  3. Visit github.com/explore and find one open-source project related to testing. Note its number of stars, contributors and the date of its last commit.
  4. Write down the meaning of: repository, commit, branch, merge, push and pull.

โ“ FAQ

๐Ÿค” What is Git in simple words?

Git is free software that keeps a complete history of changes to your project’s files, so you can see what changed, go back to earlier versions and work on several changes in parallel.

๐Ÿค” What is the difference between Git and GitHub?

Git is version control software that runs on your computer. GitHub is a website that hosts Git repositories online and adds collaboration features such as pull requests, issues and GitHub Actions.

๐Ÿค” Is Git free?

Yes. Git is free and open source. GitHub also has a free plan with unlimited public and private repositories.

๐Ÿค” Can I use Git without GitHub?

Yes. Git works fully on your own computer. You only need GitHub (or GitLab, Bitbucket) to share repositories and collaborate online.

๐Ÿค” Who uses Git?

Almost every software team, from startups to Microsoft and Google, as well as testers, DevOps engineers, data scientists and technical writers.


๐ŸŽฏ Next Steps

๐ŸŽฌ Learn Git and GitHub step by step: watch the series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

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

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

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


๐Ÿ“Œ How to Use This Cheat Sheet

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


โš™๏ธ Setup and CLI

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

Lessons: install, CLI commands, codegen


๐Ÿงช Test Structure

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

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

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

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

Lessons: first test, hooks, tags, annotations


๐ŸŽฏ Locators

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

Lessons: locators, CSS and XPath


๐Ÿ–ฑ๏ธ Actions

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

Lessons: actions, alerts, popups, iframes, tabs


โœ… Assertions

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

Lessons: assertions, visual testing


โณ Waits

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

Lesson: Playwright waits


๐Ÿ› ๏ธ playwright.config.ts Essentials

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

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

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


๐Ÿงฉ Fixtures and Page Objects

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

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

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

Lessons: POM, fixtures, custom fixtures, framework structure


๐Ÿ”Œ API Testing and Network

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

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

Lessons: API testing, network mocking


๐Ÿ“ธ Debugging, Screenshots and Reports

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

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


๐Ÿš€ CI in One Minute (GitHub Actions)

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

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


๐Ÿค– AI Tools

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

Lessons: Playwright MCP, Test Agents


๐Ÿšซ Top 10 Mistakes to Avoid

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

โ“ FAQ

๐Ÿค” Is there a Playwright cheat sheet PDF?

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

๐Ÿค” What are the most important Playwright commands to remember?

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

๐Ÿค” Which Playwright locators should I memorize first?

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


๐ŸŽฏ Next Steps

๐ŸŽฌ Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

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

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

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


๐ŸŽฏ How Experienced Interviews Differ

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

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

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


๐ŸŸข 2 Years of Experience: Strong Fundamentals

๐Ÿค” How does Playwright’s auto-waiting work, and when do you still need explicit waits?

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

๐Ÿค” What is the difference between page.locator() and page.$()?

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

๐Ÿค” Which locator strategy do you prefer and why?

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

๐Ÿค” What is strict mode in Playwright?

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

๐Ÿค” What is the difference between toHaveText and textContent with toBe?

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

๐Ÿค” How do you handle a new tab, an alert and an iframe?

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

๐Ÿค” What is a browser context and why is it important?

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

๐Ÿค” How do you run a single test, a tag or a browser from the command line?

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


๐Ÿ”ต 3 Years of Experience: Framework and Reliability

๐Ÿค” Describe the architecture of the Playwright framework you built.

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

๐Ÿค” Fixtures or hooks: when do you use which?

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

๐Ÿค” How do you avoid logging in through the UI in every test?

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

๐Ÿค” How do you handle test data in parallel runs?

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

๐Ÿค” A test is flaky in CI but passes locally. What do you do?

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

๐Ÿค” How do you combine API and UI testing?

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

๐Ÿค” When do you mock network calls?

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

๐Ÿค” How do you run tests across environments?

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

๐Ÿค” How do you implement visual testing, and how do you keep it stable?

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


๐ŸŸ  5+ Years of Experience: Architecture, Scale and Strategy

๐Ÿค” How would you design a test automation strategy for a new product?

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

๐Ÿค” How do you scale a suite of 3,000 Playwright tests?

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

๐Ÿค” How do you measure and reduce flakiness at team level?

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

๐Ÿค” How do you migrate a Selenium suite to Playwright?

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

๐Ÿค” Which design patterns do you use in a Playwright framework?

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

๐Ÿค” How do you make the framework maintainable for a large team?

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

๐Ÿค” How do you integrate Playwright into CI/CD and release decisions?

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

๐Ÿค” How are you using AI in test automation?

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


๐Ÿงฉ Scenario-Based Questions

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

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

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

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

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

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

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

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

๐Ÿค” Tests pass alone but fail when run in parallel. What is the likely cause?

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


๐Ÿ’ก Tips for the Interview

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

๐ŸŽฏ Next Steps

๐ŸŽฌ Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

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

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

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


๐Ÿ‹๏ธ How to Use This Page

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

Rules for every checkpoint:

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

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

LevelModulesBadge
๐ŸŸข Beginner1 to 5Playwright Practitioner
๐Ÿ”ต Intermediate6 to 9Playwright Engineer
๐ŸŸ  Advanced10 to 13Playwright Architect
๐ŸŸฃ Career14 to 15Interview Ready

๐ŸŸข Module 1 Checkpoint: Getting Started

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

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

๐ŸŸข Module 2 Checkpoint: JavaScript Essentials

Lessons: Variables to Promises and Async/Await

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

๐ŸŸข Module 3 Checkpoint: TypeScript for Playwright

Lessons: TypeScript Variables to TypeScript for Playwright

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

๐ŸŸข Module 4 Checkpoint: Locators and Interactions

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

On the-internet.herokuapp.com:

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

๐ŸŸข Module 5 Checkpoint: Assertions, Waits and Screenshots

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

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

๐Ÿ”ต Module 6 Checkpoint: Organizing Tests

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

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

๐Ÿ”ต Module 7 Checkpoint: Test Data, Configuration and Cross-Browser

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

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

๐Ÿ”ต Module 8 Checkpoint: Authentication and Network

Lessons: Login Sessions, Network Mocking, Passkeys

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

๐Ÿ”ต Module 9 Checkpoint: API Testing

Lessons: API Testing, API with POM

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

๐ŸŸ  Module 10 Checkpoint: Framework Design

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

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

๐ŸŸ  Module 11 Checkpoint: Debugging and Reporting

Lessons: Debugging, Trace Viewer, Reporters, Allure

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

๐ŸŸ  Module 12 Checkpoint: Parallel Execution and CI/CD

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

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

๐ŸŸ  Module 13 Checkpoint: AI-Powered Testing

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

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

๐ŸŸฃ Module 14 Checkpoint: Projects

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


๐ŸŸฃ Module 15 Checkpoint: Interview Readiness

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

โ“ FAQ

๐Ÿค” Where can I practise Playwright automation for free?

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

๐Ÿค” Are solutions provided for these assignments?

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

๐Ÿค” How long does it take to complete all assignments?

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

๐Ÿค” Do I need to finish every checkpoint before the projects?

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


๐ŸŽฏ Next Steps

๐ŸŽฌ Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

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

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

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


๐ŸŽฏ Project Brief

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

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

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


๐Ÿ”Œ The API You Will Use

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

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


๐Ÿ“‹ Requirements

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

๐Ÿ“ Step 1: Structure

hybrid-framework/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ api/
โ”‚   โ”‚   โ””โ”€โ”€ AccountApi.ts
โ”‚   โ”œโ”€โ”€ pages/
โ”‚   โ”‚   โ”œโ”€โ”€ LoginPage.ts
โ”‚   โ”‚   โ””โ”€โ”€ components/Header.ts
โ”‚   โ”œโ”€โ”€ fixtures/index.ts
โ”‚   โ””โ”€โ”€ data/userFactory.ts
โ”œโ”€โ”€ tests/
โ”‚   โ”œโ”€โ”€ api/products.api.spec.ts
โ”‚   โ”œโ”€โ”€ api/account.api.spec.ts
โ”‚   โ””โ”€โ”€ ui/login.hybrid.spec.ts
โ”œโ”€โ”€ .github/workflows/ci.yml
โ””โ”€โ”€ playwright.config.ts

โš™๏ธ Step 2: Config with API and UI Projects

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

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

๐Ÿญ Step 3: Unique Test Data with a Factory

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

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

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

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


๐Ÿ”Œ Step 4: The API Client

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

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

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

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

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

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

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

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

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

๐Ÿงฉ Step 5: Fixtures: Setup and Cleanup in One Place

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

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

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

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

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

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

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

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

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

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

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

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

๐Ÿงช Step 6: API Tests

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

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

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

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

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

๐Ÿ”— Step 7: Hybrid Tests (API Setup, UI Verification)

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

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

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

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

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


๐Ÿš€ Step 8: CI with Separate API and UI Jobs

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

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

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

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


โœ… Acceptance Checklist

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

๐Ÿ… Evaluation Rubric

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

๐Ÿš€ Stretch Goals

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

โ“ FAQ

๐Ÿค” What is a hybrid API and UI test?

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

๐Ÿค” Why use the API for test setup in Playwright?

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

๐Ÿค” How do I clean up test data in Playwright?

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

๐Ÿค” Why assert both HTTP status and responseCode?

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


๐ŸŽฏ Next Steps

๐ŸŽฌ Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

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

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

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


๐ŸŽฏ Project Brief

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

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

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


๐Ÿ“‹ Requirements

Functional coverage

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

Technical requirements


๐Ÿ“ Step 1: Create the Project and Folders

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

The layout follows framework folder structure and best practices.


โš™๏ธ Step 2: Configuration

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

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

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

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


๐Ÿ” Step 3: Log In Once (Setup Project)

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

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

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

๐Ÿงฑ Step 4: Page Objects

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

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

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

  protected abstract readonly path: string;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


๐Ÿงฉ Step 5: Fixtures and Test Data

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

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

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

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

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

๐Ÿงช Step 6: Tests

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

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

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

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

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

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

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

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

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

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


๐Ÿš€ Step 7: Continuous Integration

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


โœ… Acceptance Checklist

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

๐Ÿ… Evaluation Rubric

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

๐Ÿš€ Stretch Goals

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

โ“ FAQ

๐Ÿค” What is a good Playwright project for a portfolio?

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

๐Ÿค” Should I put this project on GitHub?

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

๐Ÿค” Why use storageState instead of logging in before each test?

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

๐Ÿค” How many tests should the project have?

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


๐ŸŽฏ Next Steps

๐ŸŽฌ Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in

Playwright Test Agents: Planner, Generator and Healer Explained

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

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


๐Ÿค What Are Playwright Test Agents?

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

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

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


โš™๏ธ Set Up the Agents

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

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

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

After initialization your project looks like this:

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

๐ŸŒฑ The Seed Test

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

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

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

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


๐Ÿ—บ๏ธ Step 1: The Planner Writes a Test Plan

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

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

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

# Cart and Checkout Test Plan

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

## Test Scenarios

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

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

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

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

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


๐Ÿ› ๏ธ Step 2: The Generator Writes the Tests

Choose the generator agent and point it at the plan:

๐Ÿ’ฌ “Generate tests for section 1 of specs/cart-and-checkout.md.”

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

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

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

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

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


๐Ÿฉน Step 3: The Healer Fixes Failing Tests

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

๐Ÿ’ฌ “Run the cart tests and fix any failures.”

The healer:

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

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


๐Ÿ” Putting It Together

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

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


โœ… Best Practices

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

๐Ÿ“ Assignment

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

โ“ FAQ

๐Ÿค” What are Playwright Test Agents?

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

๐Ÿค” How do I set up Playwright Test Agents?

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

๐Ÿค” What is the seed test in Playwright agents?

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

๐Ÿค” Can the healer agent hide real bugs?

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

๐Ÿค” What is the difference between Playwright Test Agents and Playwright MCP?

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


๐ŸŽฏ Next Steps

๐ŸŽฌ Watch the full Playwright tutorial series on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in