November 29, 2026

Agentic Deliverables Review: How to Evaluate AI-Generated Software with Confidence

Summary: As autonomous software agents take on more development tasks, reviewing their deliverables becomes an important part of software quality assurance. Reviewing only the generated code and test results is not always enough. QA teams also need to understand the decisions, assumptions, context, and tool interactions that shaped those outputs. This article explores the types of artifacts generated by autonomous agents, the challenges of reviewing them, and how agent trajectory analysis can help QA teams improve software quality and identify the root causes of defects.

Introduction

Autonomous software agents are changing how software is designed, developed, tested, and documented. They can generate source code, create test suites, retrieve relevant context, interact with development tools, and revise their work with limited human involvement.

These capabilities can speed up software delivery, but they also introduce a new QA challenge: How do we know whether an agent's deliverables are reliable, correct, and supported by sound decisions?

Traditional code reviews and automated test results remain important, but they may not provide enough visibility into how an autonomous agent reached its final output. A solution can appear correct while still containing hidden assumptions, incomplete requirements, or weaknesses in its verification approach.

This is where Agentic Deliverables Review becomes valuable. Instead of examining only the final files, QA teams review the broader set of artifacts produced during an agent's execution. They can also examine the agent's trajectory to understand the decisions and interactions that influenced the result.

Let's look at the main types of agent-generated artifacts, the challenges involved in reviewing them, and how trajectory analysis can make the process more effective.

1. Types of Software Artifacts Created by Autonomous Agents

Autonomous software agents generate several categories of artifacts throughout the software development life cycle. Each category provides a different view of the work performed and can contribute useful evidence during a quality review.

1.1 Primary Implementation Code and Architecture

This category includes the main technical outputs created or modified by an agent, such as:

  • Architectural decisions and design changes.
  • Temporary placeholders created during implementation.
  • Source code and software components.
  • Modifications to existing application structures.

Reviewing these artifacts helps QA and engineering teams understand what the agent built, which parts of the system were affected, and whether the implementation reflects the intended design.

1.2 Verification and Testing Artifacts

Autonomous agents may also create and execute tests to verify their implementation. These artifacts can include:

  • Agent-generated test suites.
  • Test execution results and reports.
  • Parity check comparisons.
  • Other outputs produced during the verification process.

These artifacts provide evidence about how the agent attempted to validate its work. However, passing tests should not automatically be treated as proof of correctness. The quality of the tests and the assumptions behind them also need to be reviewed.

1.3 Documentation and Specifications

Documentation is another important part of an agent's deliverables. It may include:

  • Generated technical documentation.
  • Written explanations of implementation choices.
  • Revised software specifications.

These documents can help reviewers understand the intended behavior and the reasoning presented by the agent. They should still be compared with the actual implementation and requirements rather than accepted at face value.

1.4 Agent Execution and Trajectory Records

One of the most valuable categories for an in-depth review is the collection of records generated while the agent performs its work. These records can include:

  • Development plans and execution steps.
  • Recorded reasoning outputs.
  • Tool calls and interactions.
  • Context retrieval logs.
  • Retries and intermediate artifact revisions.
  • Agent specifications, including harness configurations, prompt instructions, and reusable skills.

Together, these records provide a view of the agent's execution history. They help reviewers understand not only what was delivered, but also the sequence of activities and decisions that contributed to the final result.

2. Main Challenges in Reviewing Agent Deliverables

Reviewing software produced by autonomous agents introduces quality assurance challenges that are not always addressed by conventional code review practices. The main difficulty is balancing review depth with the volume of information generated during an agentic workflow.

2.1 Cognitive Debt and the Volume of Execution Steps

In highly automated workflows, agents can perform many development activities with minimal human involvement. Inspecting every execution step manually is often impractical.

However, reviewing only the final code, documentation, and test results creates another problem: cognitive debt.

Cognitive debt develops when developers and QA engineers do not have enough visibility into the decisions, assumptions, and conditions that shaped an implementation. They may see the final result without understanding how the agent arrived at it or what compromises were made along the way.

The challenge is to find a practical middle ground. QA teams need a review approach that avoids inspecting every minor activity while still providing sufficient visibility into important decisions and high-risk changes.

2.2 Shared Implicit Assumptions in Testing

Tests generated by an agent can share the same implicit assumptions as the implementation being tested. When both the code and its tests are based on the same misunderstanding of a requirement, the tests may pass even though the implementation is incorrect.

For example, an agent might misinterpret a business rule and implement that interpretation in both the application code and its test cases. The resulting test suite could report success without detecting the underlying requirement gap.

This is why test results should be reviewed alongside the test design, requirements, and assumptions used during implementation. Independent verification is particularly valuable when the consequences of an incorrect assumption are significant.

2.3 Diagnostic Ambiguity

When a defect or unexpected result appears, the final code, passing tests, and generated documentation may not explain what went wrong.

Several different causes may produce similar symptoms, including:

  • Ambiguous or misunderstood requirements.
  • Incorrect domain context.
  • Implementation mistakes.
  • Faulty verification rules or test assumptions.

Without evidence from the agent's execution history, it can be difficult to distinguish between these possibilities. Reviewers may identify the defect but struggle to determine its actual cause.

2.4 Unreliable Confidence and Explanations

An agent may provide a confidence score or generate an explanation describing why it believes its implementation is correct. Such information can be useful as a starting point, but it should not be treated as independent evidence.

A confident explanation does not guarantee that the underlying decision is correct. Similarly, a detailed narrative does not replace validation against requirements, technical constraints, and expected behavior.

Effective agent deliverables review should therefore focus on verifiable evidence rather than relying solely on the agent's own assessment of its work.

2.5 Distributed and Fragmented Evidence

Important development decisions are often spread across multiple intermediate artifacts. A relevant detail might appear in an execution plan, a context retrieval log, a tool interaction, a retry, or an earlier version of an implementation file.

When these records are reviewed separately, it becomes difficult to reconstruct the relationship between an initial decision and the final outcome.

QA teams need a way to connect these pieces of evidence so they can follow the development history and understand how specific decisions influenced the delivered software.

3. How Agent Trajectories Improve Software Quality Assurance

An agent trajectory is the recorded history of an agent's execution. It can include reasoning steps, tool usage, retrieved context, artifact revisions, and test results.

Rather than treating these records as incidental execution logs, QA teams can use them as first-class evidence artifacts. This creates an opportunity to review the development process more effectively without requiring manual inspection of every individual step.

3.1 Targeted Scrutiny of Consequential Decisions

Instead of reviewing every execution step with the same level of attention, QA teams can use trajectory analysis to identify decisions that deserve closer scrutiny.

Review priorities can be based on factors such as:

  • Impact: How significantly could the decision affect application behavior or business outcomes?
  • Scope: How many components, services, or workflows could be affected?
  • Uncertainty: How much ambiguity or incomplete information was involved?
  • Reversibility: How difficult would it be to undo the decision if it proved incorrect?
  • Validation effort: How much independent verification is needed to establish confidence in the result?

This risk-based approach helps reviewers spend more time on consequential decisions and less time on routine execution details.

3.2 Root-Cause Diagnosis

Agent trajectories can connect the final implementation to the context retrieved and decisions made during execution. This connection gives reviewers a stronger basis for investigating defects.

For example, when an implementation does not meet a requirement, trajectory evidence may help determine whether the problem originated from:

  • A misunderstanding of the original specification.
  • Retrieval of outdated or irrelevant context.
  • An incorrect implementation decision.
  • A weakness in the verification approach.

Being able to distinguish between these causes is important. Fixing the code alone may resolve one defect, but identifying the underlying cause can help prevent similar problems in future agentic workflows.

3.3 Exposing Implicit Assumptions

Some of the most important risks in agent-generated software are not immediately visible in the final code. An agent may make an unstated simplification, skip a particular validation step, or rely on incomplete context.

Trajectory analysis can help reveal these assumptions by showing the context used, the decisions recorded, and the changes made during execution.

Reviewers can then compare those assumptions with the actual requirements and expected system behavior. This is especially useful when the final implementation and its generated tests appear consistent but may share the same underlying misunderstanding.

3.4 Building Continuous Feedback Loops

Agent trajectory review should not end when a particular deliverable is approved or rejected. Findings from one review can be used to improve future agent executions.

For example, recurring issues may lead to updates in:

  • Prompt instructions and agent specifications.
  • Tool-use constraints.
  • Context retrieval parameters.
  • Verification rules and quality gates.

These improvements create a feedback loop between QA findings and agent configuration. Over time, the goal is to reduce repeated errors and make agent-generated deliverables more reliable.

Conclusion

As autonomous software agents become more involved in development and testing, reviewing their deliverables requires more than checking the final code and whether the tests pass.

QA teams need to consider the complete set of artifacts generated during execution, including implementation code, testing outputs, documentation, and agent trajectory records. Each category provides a different type of evidence about the quality of the delivered work.

Agent trajectories are particularly useful because they help reviewers understand the decisions, context, tool interactions, and revisions behind the final output. They support targeted risk-based reviews, more effective root-cause diagnosis, identification of hidden assumptions, and continuous improvements to agent specifications and verification processes.

The key point is simple: reviewing agentic deliverables should involve both the final result and the evidence of how that result was produced. This broader perspective can help QA teams build greater confidence in autonomous software development without attempting to inspect every execution step manually.

How is your team reviewing software deliverables produced by autonomous agents? Are you checking only the final artifacts, or are you also examining agent trajectories and execution evidence? Share your experience or questions in the comments.

If you want any of the following, send a message using the Contact Us (right pane) or message Inder P Singh (Remote Agentic AI Lead & Enterprise AI Solutions Architect) in LinkedIn at https://www.linkedin.com/in/inderpsingh/

  • Production-oriented Test Automation templates with playbooks
  • Runnable Test Automation projects for your portfolio
  • Deep-dive hands-on Test Automation Training
  • Resume Updates

November 21, 2026

PowerShell Commands for SDET and Test Automation

Summary: PowerShell is an essential tool for SDETs and test automation engineers working with Windows-based projects. From navigating folders and managing files to running Playwright tests, executing Maven commands, checking APIs, inspecting logs, and troubleshooting processes, PowerShell can make everyday automation tasks faster and easier. This practical post covers useful PowerShell commands with examples for Playwright, Selenium, Node.js, Java, API testing, and Git.

If you work in software testing or test automation, you probably spend a lot of time opening project folders, checking configuration files, running automated tests, inspecting reports, and investigating failures. Many of these activities can be performed directly from the PowerShell terminal.

PowerShell is more than a place to execute commands. It is both a command-line shell and a scripting language that helps you automate repetitive tasks, inspect project files, manage processes, and troubleshoot test environments.

In this post, we will start with everyday PowerShell commands and gradually move towards practical SDET activities. You will learn how to navigate project folders, manage files, search source code, run Playwright and Selenium tests, inspect JSON, perform API checks, work with Git, and investigate common automation problems. The examples use Windows PowerShell syntax and Windows file paths. Replace the sample paths and file names with the actual locations on your computer. Run the commands from the PowerShell terminal on the machine where your project is stored.

Check out my Test Automation Playbooks & Repos on GitHub. Now, let's continue with this post.

What You Will Learn

  • Basic PowerShell commands and folder navigation
  • Creating, copying, moving, renaming, and deleting files
  • Searching source code, test files, and execution logs
  • Filtering, sorting, counting, and saving command output
  • Working with variables, conditions, and environment variables
  • Running Node.js, npm, and Playwright commands
  • Executing Java, Selenium, Maven, and Git commands
  • Performing basic API and network checks
  • Inspecting JSON configuration and troubleshooting processes
  • Practical PowerShell workflows for everyday SDET work

Understanding PowerShell Commands

PowerShell commands are generally written using a Verb-Noun naming convention. For example:

  • Get-ChildItem: Gets files and folders.
  • Set-Location: Changes the current location.
  • Get-Content: Reads file contents.
  • Remove-Item: Deletes files or other items.
  • Test-Path: Checks whether a path exists.

PowerShell also supports convenient aliases for frequently used commands. For example, dir, cd, type, and mkdir are familiar shortcuts for PowerShell commands.

Aliases are useful when working interactively, but learning the underlying command names makes your scripts easier to understand and maintain.

1. Open PowerShell and Understand the Prompt

When you open PowerShell, you may see a prompt similar to this:

PS E:\QATraining\APIAutomationFramework>

This tells you that your current location is E:\QATraining\APIAutomationFramework.

The current location is important because relative paths such as .\tests refer to folders inside the current directory.

Show the current location:

Get-Location

Short alias:

pwd

Clear the terminal display:

Clear-Host

Alias:

cls

Show PowerShell version details:

$PSVersionTable

Show the current user:

whoami

These commands are useful when you start working on a project or need to confirm which PowerShell environment and user account are active.

2. Change Drives and Move Between Folders

Before running test automation commands, you need to navigate to the correct project directory. PowerShell makes it straightforward to switch drives and move between folders.

Switch to drive E:

E:

Switch to drive C:

C:

Change to a project folder:

Set-Location "C:\Training\PlaywrightTSAPIFramework"

Short form:

cd "C:\Training\PlaywrightTSAPIFramework"

Move up one directory:

Set-Location ..

Short form:

cd ..

Move up two directory levels:

Set-Location ..\..

Move to the current user's home folder:

Set-Location $HOME

Move to the root of the current drive:

Set-Location \

Return to the previous location:

Pop-Location

You can also save a location temporarily and return to it later.

Push-Location "C:\Training"
Get-Location
Pop-Location

Important: Set-Location changes the current working location. It does not move or rename a directory on your computer.

3. List Files and Folders

When you start working on a test automation project, one of the first things you may want to do is inspect its folder structure.

List files and folders in the current directory:

Get-ChildItem

Common alias:

dir

Another alias:

ls

List names only:

Get-ChildItem -Name

List files only:

Get-ChildItem -File

List folders only:

Get-ChildItem -Directory

Include hidden items:

Get-ChildItem -Force

List items in a specific folder:

Get-ChildItem "C:\Training\Playwright\Deliverables"

List TypeScript test specifications:

Get-ChildItem .\tests -Filter *.spec.ts

Find Java files recursively:

Get-ChildItem . -Recurse -File -Filter *.java

Find TypeScript files recursively:

Get-ChildItem . -Recurse -File -Filter *.ts

Display a folder tree:

tree

Display folders and files:

tree /F

Display the tree for a particular folder:

tree "C:\Training\PlaywrightTSAPIFramework" /F

Practical tip: The tree /F command can generate a large amount of output in a big project. Start from the relevant project directory rather than the root of your drive.

4. Create, Copy, Move, Rename, and Delete Files and Folders

Test automation engineers frequently create test data folders, back up test files, move reports, and clean up temporary files. These PowerShell commands help you manage those tasks.

Create a folder:

New-Item -ItemType Directory -Path .\notes

Short alias:

mkdir .\notes

Create an empty file:

New-Item -ItemType File -Path .\notes\session-notes.txt

Create a folder only if it does not already exist:

New-Item -ItemType Directory -Path .\artifacts -Force

Copy a file:

Copy-Item .\tests\petstore-list.spec.ts .\tests\petstore-list.backup.spec.ts

Copy a folder and its contents:

Copy-Item .\test-data .\test-data-backup -Recurse

Move a file:

Move-Item .\notes\old-notes.txt .\notes\archive\old-notes.txt

Rename a file:

Rename-Item .\notes\old-name.txt new-name.txt

Delete one file:

Remove-Item .\notes\temporary.txt

Delete a folder and its contents:

Remove-Item .\temporary-folder -Recurse

Safety reminder: Always verify your current directory and the exact target before using Remove-Item. Avoid broad deletion commands. Do not use -Recurse or -Force unless you understand exactly what will be removed.

Never delete folders such as node_modules, test results, source files, or reports simply because an example command suggests it. First confirm that the target is disposable and that you have any required backup.

5. Check Paths and File Metadata

Before running a test suite or reading a configuration file, it is useful to confirm that the required file or folder actually exists.

Check whether a file exists:

Test-Path .\playwright.config.ts

Check whether a folder exists:

Test-Path .\tests

Check an absolute path:

Test-Path "C:\Training\PlaywrightTSAPIFramework\package.json"

Show file details such as length and last modification time:

Get-Item .\package.json

Display selected file details:

Get-Item .\package.json | Select-Object FullName, Length, LastWriteTime

Find files by extension in the current project:

Get-ChildItem . -Recurse -File -Filter *.spec.ts

Find files whose names contain "petstore":

Get-ChildItem . -Recurse -File | Where-Object { $_.Name -like "*petstore*" }

These commands are particularly useful when working with large Playwright or Selenium projects where test files, fixtures, configuration files, and reports are stored in different folders.

Note: Check out the videos in my Software and Testing Training channel.

6. Read File Contents

Reading configuration files and test scripts is a regular part of test automation work. PowerShell provides Get-Content for displaying file contents.

Display a text file:

Get-Content .\package.json

Familiar alias:

type .\package.json

Note: Get-Content is the preferred PowerShell command. The type alias is convenient, but it is not the same as every external program named type.

Read the entire file as one string:

Get-Content .\package.json -Raw

Read the first 20 lines:

Get-Content .\test-run.log -TotalCount 20

Read the last 50 lines:

Get-Content .\test-run.log -Tail 50

Follow a log as new lines are written:

Get-Content .\test-run.log -Wait

Press Ctrl+C to stop waiting for new log entries.

Read a Playwright configuration file:

Get-Content .\playwright.config.ts -Raw

Read a specific test:

Get-Content .\tests\petstore-crud.spec.ts -Raw

Open a file in Notepad:

notepad .\playwright.config.ts

Practical tip: If a file is long, read only the relevant section or use Select-String to locate a keyword. Dumping an entire large project into the terminal is rarely helpful.

7. Search Source Code and Logs

When a test fails, you may need to search logs for errors, find assertions in test scripts, or locate unfinished work marked with TODO comments.

Search a file for a word:

Select-String -Path .\test-run.log -Pattern "failed"

Alias:

sls -Path .\test-run.log -Pattern "failed"

Search all Playwright specifications for assertions:

Select-String -Path .\tests\*.spec.ts -Pattern "expect"

Search TypeScript and Java files recursively for TODO or FIXME:

Get-ChildItem . -Recurse -File -Include *.ts,*.java |
    Select-String -Pattern "TODO|FIXME"

Search logs for common failure terms:

Select-String -Path .\test-run.log -Pattern "Error|failed|timeout|expect"

Display matching lines with line numbers:

Select-String -Path .\tests\*.spec.ts -Pattern "expect" |
    Select-Object Path, LineNumber, Line

Note: Select-String searches without case sensitivity by default. Use -CaseSensitive when the letter case must match.

For an SDET, these commands can save time when investigating a large test suite. Instead of manually opening several files, you can search for the relevant error or assertion directly from the terminal.

8. Display, Filter, Sort, and Count Results

PowerShell makes it easy to filter and organize command output. This is especially useful when a project contains hundreds of test files or execution artifacts.

Show the first 10 files:

Get-ChildItem -File | Select-Object -First 10

Show the most recently modified files first:

Get-ChildItem -File |
    Sort-Object LastWriteTime -Descending |
    Select-Object -First 10 Name, Length, LastWriteTime

Filter for log files:

Get-ChildItem -File | Where-Object { $_.Extension -eq ".log" }

Count test specification files:

(Get-ChildItem .\tests -Filter *.spec.ts -File).Count

Count files recursively:

(Get-ChildItem . -Recurse -File).Count

Count lines in a text file:

(Get-Content .\test-run.log).Count

Display only file names and lengths:

Get-ChildItem -File | Select-Object Name, Length

Understand the PowerShell pipeline:

PowerShell pipelines pass objects between commands. For example, Get-ChildItem returns file objects. This allows Sort-Object to sort files by their actual LastWriteTime property instead of trying to interpret formatted terminal text.

9. Save Output to Files and Copy It

Sometimes you need to save command output for later analysis, share a directory listing, or capture information while a test suite is running.

Write command output to a text file, replacing its contents:

Get-ChildItem -Name | Out-File .\file-list.txt

Append output to a file:

"Test run started" | Out-File .\test-notes.txt -Append

Save command output while still displaying it:

Get-ChildItem | Tee-Object -FilePath .\directory-list.txt

Copy text to the Windows clipboard:

Get-Content .\package.json -Raw | Set-Clipboard

Copy a log to the clipboard:

Get-Content .\test-run.log -Raw | Set-Clipboard

Security reminder: Clipboard content can contain sensitive information. Inspect and sanitize logs or configuration files before sharing them with Claude or any other external service. Remove passwords, tokens, API keys, and customer information.

You can get free QA Test Automation guides on our Company Page on LinkedIn. 

10. Environment Variables and the Current Session

Environment variables are commonly used in test automation projects to store settings such as environment names, CI flags, URLs, and configuration values.

PowerShell provides a convenient way to read and update environment variables for the current session.

Show the current value of an environment variable:

$env:CI

Show the current PATH:

$env:PATH

Show all environment variables:

Get-ChildItem Env:

Set an environment variable for the current PowerShell session:

$env:CI = "true"

Remove it from the current session:

Remove-Item Env:CI

Important: These changes normally disappear when the PowerShell session ends. Persistent environment variable changes are a separate operation. Avoid changing persistent settings unless you understand the effect on your machine and other applications.

11. Basic PowerShell Variables and Conditions

PowerShell is also a scripting language. You can store values in variables, check conditions, and loop through files. These features are useful when creating small scripts for repetitive test automation tasks.

Store a project path in a variable:

$projectPath = "C:\Training\PlaywrightTSAPIFramework"
Set-Location $projectPath

Store command output:

$specFiles = Get-ChildItem .\tests -Filter *.spec.ts
$specFiles.Count

Check whether a configuration file exists:

if (Test-Path .\package.json) {
    "package.json exists"
} else {
    "package.json was not found"
}

Loop through specification files:

Get-ChildItem .\tests -Filter *.spec.ts | ForEach-Object {
    Write-Output $_.Name
}

Note: PowerShell variables begin with $. Strings can use single or double quotes. Double-quoted strings expand variables, while single-quoted strings are treated as literal text.

12. Check Installed Tools

Before running a test automation project, confirm that the required tools are installed and available from your terminal.

Check Node.js and npm:

node --version
npm --version

Find the executables PowerShell will run:

Get-Command node
Get-Command npm
Get-Command npx

Find Java:

java -version

Find the Java compiler:

javac -version

Check Maven:

mvn -version

Check Git:

git --version

What if a command is not recognized?

Note: Depending on command resolution, PowerShell can attempt to execute npm.ps1 or npx.ps1, which may be blocked by the execution policy.


# Alternative: use the Windows command launchers
npm.cmd --version
npx.cmd --version
The user can then use:

npm.cmd install
npm.cmd run test:api
npx.cmd playwright test

This provides an alternative without requiring the user to weaken their PowerShell execution policy.

If PowerShell reports that a command is not recognized, the tool may not be installed, or its installation directory may not be included in the system PATH. After installing a tool or changing PATH, open a new terminal and check again.

13. Node.js, npm, and Playwright Project Commands

PowerShell is particularly useful when working with Node.js and Playwright automation projects. You can install dependencies, execute test suites, run individual specifications, and generate reports directly from the terminal.

First, navigate to your Playwright project folder.

C:
cd "C:\Training\PlaywrightTSAPIFramework"

Check the current folder:

Get-Location

List project files:

dir

Read package.json:

Get-Content .\package.json -Raw

Install dependencies from package.json:

npm install

Check installed top-level packages:

npm list --depth=0

Run a package script:

npm run test:api

Run the default test script:

npm test

The available npm scripts are defined in the project's package.json file. You can inspect them using:

Get-Content .\package.json -Raw

Run Playwright Test directly:

npx playwright test

List tests without executing them:

npx playwright test --list

Run one specification:

npx playwright test .\tests\petstore-list.spec.ts --reporter=list

Run tests by title or tag:

npx playwright test --grep "@api"

Run tests whose title matches a phrase:

npx playwright test --grep "Create, update"

Exclude tests matching a tag:

npx playwright test --grep-invert "@slow"

Run with a visible browser where supported by the test configuration:

npx playwright test --headed

Open Playwright's interactive debugger:

npx playwright test --debug

Open the HTML report from the most recent run, if it exists:

npx playwright show-report

If your package.json defines a report script such as "report": "playwright show-report", you can use its shortcut:

npm run report

Run tests and save terminal output to a log while keeping it visible:

npx playwright test 2>&1 | Tee-Object -FilePath .\test-run.log

Read the captured log:

Get-Content .\test-run.log -Raw

Note: Playwright CLI options can vary by version. Use the following command to inspect the options supported by your installed version:

npx playwright test --help

14. Playwright Debugging and Failure Artifacts

When a Playwright test fails, you may need to isolate the failing specification, inspect the generated artifacts, and review the trace or HTML report.

List tests and their titles:

npx playwright test --list

Run a single failing specification with the list reporter:

npx playwright test .\tests\petstore-crud.spec.ts --reporter=list

Run a specific test title using a grep pattern:

npx playwright test --grep "Requesting a missing pet"

Inspect the configured output directories:

Get-Content .\playwright.config.ts -Raw

List files created in test-results:

Get-ChildItem .\test-results -Recurse -File

List files in the HTML report folder:

Get-ChildItem .\playwright-report -Recurse -File

Open a trace using the installed Playwright CLI:

npx playwright show-trace .\test-results\path-to-trace.zip

Note: Replace the example trace path with the actual ZIP file path generated by your test run. A trace file will exist only if your configuration or execution settings generated one.

These commands are useful when you need to investigate a failed test without running the entire automation suite repeatedly.

15. Java and Selenium Project Commands

If you work with Selenium WebDriver and Java, PowerShell can also be used to compile, execute, and troubleshoot your Java-based automation projects.

Check Java:

java -version
javac -version

For a Maven project, navigate to the folder containing pom.xml before running the following commands.

Run Maven tests:

mvn test

Run Maven tests with additional error output:

mvn test -e

Run a selected Maven test class:

mvn -Dtest=LoginTest test

Read Maven configuration:

Get-Content .\pom.xml -Raw

Important: Use commands appropriate to your project. Do not run Maven commands in a project that does not contain a Maven build file, or Gradle commands in a project that does not contain a Gradle build file.

16. Git Commands for Test Automation Work

Git is an important part of most modern test automation workflows. SDETs use it to track changes to test scripts, review updates, inspect branches, and collaborate with development teams.

You can execute common Git commands directly from PowerShell.

Check whether the current folder is a Git repository and view working-tree status:

git status

Show changed file names:

git diff --name-only

Show code changes:

git diff

Show the last five commits:

git log -5 --oneline

List branches:

git branch

Safety reminder: Avoid commands such as git reset, git clean, and git checkout when you are unsure of their impact. Some Git operations can discard local changes. Before sharing command output, also check that no secrets or sensitive file names are exposed.

17. JSON and Configuration Inspection

Modern automation frameworks commonly use JSON configuration files. For example, Node.js projects use package.json to define dependencies, scripts, and project metadata.

PowerShell can read and parse JSON, allowing you to inspect individual properties without manually searching through the entire file.

Read package.json:

Get-Content .\package.json -Raw

Parse JSON into a PowerShell object:

$package = Get-Content .\package.json -Raw | ConvertFrom-Json
$package.name
$package.scripts

Show the test script:

$package = Get-Content .\package.json -Raw | ConvertFrom-Json
$package.scripts.test

Convert an object to formatted JSON:

$package | ConvertTo-Json -Depth 10

Practical tip: Parsing JSON is useful for inspecting configuration, but avoid editing package.json through ad hoc string replacement. Preserve valid JSON syntax and review the changes after editing the file.

18. Process and Port Troubleshooting

Sometimes a test automation problem is not caused by the test script itself. A process may already be running, or a port required by your application may be occupied.

PowerShell provides commands that help you inspect running processes and listening ports.

Find running processes by name:

Get-Process node

Find processes by partial name:

Get-Process | Where-Object { $_.ProcessName -like "*node*" }

Find processes listening on port 3000:

Get-NetTCPConnection -LocalPort 3000 -State Listen

Find the process ID associated with a listening connection:

Get-NetTCPConnection -LocalPort 3000 -State Listen |
    Select-Object LocalAddress, LocalPort, OwningProcess

Look up a process using its process ID:

Get-Process -Id 1234

Replace 1234 with the actual OwningProcess value returned by the previous command.

Safety reminder: Do not terminate a process until you have identified what it does and confirmed that stopping it will not affect another application or test execution.

19. Errors, Exit Codes, and Command History

When running automation commands, you need to know whether the previous operation succeeded or failed. PowerShell provides variables and commands that help you inspect execution status and review command history.

Show the exit code of the most recently completed native executable:

$LASTEXITCODE

For many command-line tools, an exit code of 0 indicates success, while a non-zero value indicates failure. However, the exact meaning of an exit code depends on the tool.

Check whether the previous PowerShell operation reported success:

$?

Show recent commands from the current session:

Get-History

Repeat a history entry by ID:

Invoke-History 3

Replace 3 with the intended history ID.

Important: Inspect a history command before repeating it, especially if it could modify or delete files, change configuration, or affect running processes.

20. Practical PowerShell Workflows for SDETs

Now that we have covered the individual commands, let's combine them into practical workflows that you can use during everyday test automation activities.

Workflow A: Navigate to a Project and Inspect It

Use the following commands to open your Playwright project and inspect its structure.

C:
cd "C:\Training\PlaywrightTSAPIFramework"
Get-Location
dir
tree /F

Workflow B: Inspect Key Playwright Files

When you join an existing automation project or investigate a test failure, you may need to inspect the package configuration, Playwright settings, fixtures, and test specifications.

Get-Content .\package.json -Raw
Get-Content .\playwright.config.ts -Raw
Get-Content .\fixtures\petstore-fixtures.ts -Raw
Get-Content .\tests\petstore-crud.spec.ts -Raw

Workflow C: Run the API Suite and Capture Output

Run your API test suite and save the terminal output to a log file while keeping it visible.

npm run test:api 2>&1 | Tee-Object -FilePath .\test-run.log

Then inspect the last 80 lines of the log:

Get-Content .\test-run.log -Tail 80

Workflow D: Find Failures in a Log

Instead of reading the entire log, search for common failure-related terms.

Select-String -Path .\test-run.log -Pattern "failed|Error|timeout|expect"

Workflow E: Run a Single Test and Open the Report

When you identify a failing specification, run it independently before executing the complete test suite again.

npx playwright test .\tests\petstore-crud.spec.ts --reporter=list
npm run report

The report command works only if package.json defines the report script and a report has already been generated by a previous test run.

Workflow F: Share Relevant Context with Claude

When asking an AI assistant to help investigate a test failure, sharing the relevant source code and a small section of the execution log can provide useful context.

Get-Content .\tests\petstore-crud.spec.ts -Raw
Get-Content .\utils\api-assertions.ts -Raw
Get-Content .\test-run.log -Tail 80

Copy only the relevant output. Remove or mask API keys, passwords, tokens, private URLs, customer data, and other confidential information before sharing it with Claude or any external service.

21. PowerShell Safety and Best Practices for Test Automation Engineers

PowerShell can save time, but commands that modify files, delete folders, or terminate processes should always be used carefully. A small mistake in the terminal can affect an entire project or test environment.

Keep these practical guidelines in mind:

  • Check Get-Location before running file operations.
  • Use quotation marks around paths containing spaces.
  • Prefer Get-Content -Raw when you need the full contents of a small text file as one string.
  • Avoid dumping large directories or node_modules folders into the terminal.
  • Never share secrets from .env files, authorization headers, tokens, or credentials.
  • Treat AI-generated commands and code as proposals that need review before execution.
  • Avoid destructive commands unless you understand the target and their consequences.
  • Run the narrowest relevant test first, then execute the broader suite.
  • Preserve the exact error output and relevant logs when troubleshooting.
  • Remember that a passing test confirms only the behavior covered by its assertions.

Conclusion

PowerShell is a valuable tool for SDETs and test automation engineers, particularly when working with Windows-based development and testing environments. It helps you perform everyday activities such as navigating folders, managing files, reading configuration, searching logs, and inspecting project structures.

Its usefulness goes well beyond basic command-line operations. You can use PowerShell to install and run Node.js dependencies, execute Playwright tests, troubleshoot Selenium and Maven projects, inspect API responses, check network connectivity, investigate running processes, and work with Git.

You do not need to memorize every command at once. Start with the commands you use most often, such as Get-Location, Get-ChildItem, Get-Content, Select-String, and Test-Path. Then gradually introduce pipelines, variables, and troubleshooting commands into your daily workflow.

With regular practice, PowerShell can become one of the most useful tools in your test automation toolkit, helping you spend less time on repetitive terminal tasks and more time building reliable automation solutions.

Frequently Asked Questions About PowerShell for Test Automation

1. Why should an SDET learn PowerShell?

PowerShell helps SDETs manage project files, execute automation commands, inspect logs, configure environment variables, and troubleshoot test environments. It is particularly useful for engineers working on Windows-based automation projects.

2. Can I run Playwright tests using PowerShell?

Yes. You can use PowerShell to navigate to your Playwright project, install dependencies with npm, execute tests using npx playwright test, run individual specifications, and open generated HTML reports.

3. Can PowerShell be used for Selenium automation?

Yes. PowerShell can execute Java and Maven commands used by Selenium projects. For example, you can run mvn test from the directory containing your Maven build file.

4. What is the difference between Get-ChildItem and dir?

Get-ChildItem is the PowerShell command used to retrieve files and folders. dir is a convenient alias that performs the same PowerShell operation.

5. How can I search test execution logs in PowerShell?

Use Select-String with the log file path and a search pattern. For example, Select-String -Path .\test-run.log -Pattern "failed|Error|timeout" helps locate common failure messages.

6. Can PowerShell send API requests?

Yes. Commands such as Invoke-RestMethod and Invoke-WebRequest can send HTTP requests and inspect API responses. They are useful for quick manual checks, although they do not replace a properly designed automated API test suite.

7. How can I check whether a port is already in use?

You can use Get-NetTCPConnection to inspect listening connections. For example, Get-NetTCPConnection -LocalPort 3000 -State Listen checks for a process listening on port 3000.

8. How do I save PowerShell command output to a log file?

You can use Out-File to save output or Tee-Object to save output while displaying it in the terminal. For example, Get-ChildItem | Tee-Object -FilePath .\directory-list.txt does both.

Have you used PowerShell in your test automation projects? Share your most useful commands, troubleshooting tips, or questions in the comments. Your experience may help other SDETs and automation engineers improve their daily workflows.

If you want any of the following, send a message using the Contact Us (right pane) or message Inder P Singh (19 years' experience in Test Automation and QA) in LinkedIn at https://www.linkedin.com/in/inderpsingh/

  • Production-oriented Test Automation templates with playbooks
  • Runnable Test Automation projects for your portfolio
  • Deep-dive hands-on Test Automation Training
  • PowerShell Resume Updates

October 28, 2026

TypeScript Interview Questions and Answers for Playwright Test Automation

Summary: Learn TypeScript for test automation with practical Playwright examples. This post explains variables, classes, imports, async and await, conditional statements, arrays, loops, functions, interfaces, union types, error handling, and API testing. Explore how these TypeScript fundamentals help you build readable, reusable, and maintainable Playwright UI and API automation tests. 

If you're new to Playwright, view my Playwright Test Automation video below or read my Playwright features blog post. Then read on.

You can run my free Playwright playbook on GitHub to get an understanding of how Playwright works end to end.

Introduction

Are you wondering how much TypeScript you need to know to write effective automation tests? You can start with a few core concepts and build your skills as your test framework grows.

Question: What is TypeScript, and how does it help with Playwright test automation?

TypeScript adds static type checking to JavaScript and helps you catch certain coding mistakes before running your tests. It also provides useful features for organizing reusable components, defining test data, and maintaining a Page Object Model.

This post explains TypeScript concepts through practical examples using the Swag Labs demo application and the Swagger PetStore API. You will learn how to use variables, classes, imports, asynchronous operations, conditional logic, arrays, loops, functions, interfaces, and error handling in Playwright automation.

1. Variables in TypeScript

Question: What is a variable in TypeScript?

A variable stores a value that your test needs to use. TypeScript supports const and let for declaring variables.

  • const: Use it when you do not need to reassign the variable.
  • let: Use it when the variable's value needs to be reassigned.

Question: What are type annotations in TypeScript?

Type annotations such as : string and : number tell TypeScript what type of value a variable is expected to hold. These annotations help the compiler and editor identify certain mistakes before the test runs.

Example: Declaring variables for a login test

const appUrl: string = 'https://www.saucedemo.com/';
const username: string = 'standard_user';
const password: string = 'secret_sauce';

// TypeScript error: const variables cannot be reassigned.
// appUrl = 'https://www.example.com';

let attemptCount: number = 0;
attemptCount = attemptCount + 1;

console.log(attemptCount); // 1

The const keyword prevents reassignment of the variable binding. It does not make every object or array stored in that variable immutable. Also, TypeScript checks types during development, but type annotations do not automatically validate external data at runtime.

Follow Inder P Singh (19 years' experience in Test Automation) to get the new AI-based Testing, Test Automation and QA guides.

2. Classes in TypeScript

Question: What is a class in TypeScript, and how can it be used in a Playwright framework?

A class groups related data and behavior into a reusable unit. In a Playwright automation framework, a class can represent a page, store a reference to the page, define locators, and provide methods for interacting with the application.

Question: What is the purpose of a constructor in a TypeScript class?

The class defines the structure, while the constructor initializes an object when it is created.

Example: Creating a simple LoginPage class

export class LoginPage {
    readonly appName: string;

    constructor() {
        this.appName = 'Swag Labs';
    }

    getAppName(): string {
        return this.appName;
    }
}

In this example, appName is a readonly property. The constructor assigns its value, and getAppName() returns it.

A practical Page Object would usually receive a Playwright Page instance through its constructor and expose methods for actions such as entering credentials and clicking the login button. This keeps page interactions separate from test scenarios.

3. Import Statements in TypeScript

Question: What is an import statement in TypeScript, and why is it useful in test automation?

Import statements allow one file to use code or types exported by another module or package. They help divide an automation framework into smaller, reusable files.

Importing Playwright Test

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

Here, test provides the Playwright test runner, while expect provides the assertion API.

Importing a Page Object

import { LoginPage } from '../pages/LoginPage';

The corresponding module must export the LoginPage class. Once imported, the test can create an instance and reuse its methods.

For example, instead of repeating login locators in multiple test files, we can keep them in one Page Object and update them there when the application's UI changes.

4. Async and Await in Playwright

Question: Why do Playwright browser interactions and API requests commonly use async and await?

Playwright browser interactions and API requests are asynchronous. This means an operation may take time to complete, and the test must handle that operation before continuing with dependent steps.

Question: What do async and await mean in TypeScript, and does await block the entire Node.js runtime?

The async keyword allows a function to use await. The await keyword pauses the current asynchronous function until the awaited Promise settles. It does not block the entire Node.js runtime.

Example: Logging in to Swag Labs

await page.goto('https://www.saucedemo.com/');

await page.locator('[data-test="username"]')
    .fill('standard_user');

await page.locator('[data-test="password"]')
    .fill('secret_sauce');

await page.locator('[data-test="login-button"]')
    .click();

// Copyright © 2026 Inder P Singh await expect(page).toHaveURL(/inventory.html/);

Each browser operation is awaited before the next dependent operation continues. This makes the intended sequence clear: open the application, enter the username and password, click the login button, and verify the resulting URL.

In Playwright Test, these statements should normally appear inside an asynchronous test or helper function.

5. JavaScript vs. TypeScript

Question: What is the difference between JavaScript and TypeScript?

JavaScript is the programming language used by Node.js to execute Playwright code. TypeScript extends JavaScript with features such as static type checking, type annotations, interfaces, and improved editor support.

TypeScript helps catch certain errors during development and makes complex automation projects easier to maintain. Its types are generally removed during compilation or transformation, so runtime assertions are still needed to verify that an application behaves as expected.

Want to learn more? View the videos and tutorials on the Software and Testing Training YouTube channel.

6. Control Flow in TypeScript

Question: What is control flow, and why is it useful in test automation?

Control flow allows an automation script to make decisions and choose which actions to execute. The most common constructs include if, else, else if, and logical operators.

In Playwright, conditional logic can be useful when a test intentionally handles different expected outcomes based on its test data. However, it should not be used to silently skip failed assertions or hide unexpected application behavior.

If and else statements

Question: How do if and else statements help select an expected test outcome?

An if statement executes a block when its condition evaluates to true. An else statement provides an alternative path when the condition is false.

Example: Handling different login outcomes

if (user.username === 'locked_out_user') {
    const errorMsg = page.locator('[data-test="error"]');

    await expect(errorMsg).toContainText(
        'Sorry, this user has been locked out'
    );
} else {
    await expect(page).toHaveURL(/inventory.html/);
}

This example assumes the login action has already been performed and that the user object is available.

The condition checks whether the username is locked_out_user. If it matches, the test verifies the expected error message. Otherwise, it verifies successful navigation to the inventory page.

The === operator checks strict equality. The Playwright assertion is what verifies the expected application behavior; the conditional statement simply selects the appropriate expectation.

Using multiple conditions with else if

Question: What is the purpose of an else if statement?

An else if statement allows the test to evaluate additional conditions in sequence. The first condition that evaluates to true determines which block executes.

if (user.username === 'locked_out_user') {
    await expect(
        page.locator('[data-test="error"]')
    ).toContainText(
        'Sorry, this user has been locked out'
    );

} else if (user.username === 'standard_user') {
    await expect(page).toHaveURL(/inventory.html/);

} else {
    await expect(page).toHaveURL(/inventory.html/);
}

The first branch handles the locked-out user, the second handles the standard user, and the final branch handles other usernames.

In a production framework, make sure each branch reflects a clearly defined test scenario. If different user types are expected to produce different outcomes, encode those expectations in the test data rather than assuming that every unrecognized username should succeed.

Logical operators in TypeScript

Question: What do the logical operators &&, ||, and ! mean in TypeScript?

Logical operators combine or modify Boolean conditions.

  • &&: Both conditions must be true.
  • ||: At least one condition must be true.
  • !: Negates a Boolean condition.

Example: Checking multiple login conditions

if (
    user.username === 'standard_user' &&
    user.password === 'secret_sauce'
) {
    await expect(page).toHaveURL(/inventory.html/);
}

Both conditions must be true before the code inside the if block executes.

7. Arrays in TypeScript

Question: What is an array in TypeScript, and how can it be used to manage test data?

An array stores multiple values in one collection. Arrays are useful in test automation for managing product names, usernames, URLs, expected messages, and other test data.

Example: Storing product names

const products: string[] = [
    'Sauce Labs Backpack',
    'Sauce Labs Bike Light',
    'Sauce Labs Bolt T-Shirt'
];

console.log(products[0]);      // Sauce Labs Backpack
console.log(products[1]);      // Sauce Labs Bike Light
console.log(products.length);  // 3

The string[] annotation indicates that the array contains strings. Array indexing starts at zero, so products[0] accesses the first element. The length property returns the number of elements.

Adding and checking array values

const products: string[] = [
    'Sauce Labs Backpack',
    'Sauce Labs Bike Light'
];

products.push('Sauce Labs Bolt T-Shirt');

console.log(products.length); 
// 3

console.log(
    products.includes('Sauce Labs Backpack')
);
// true

The push() method adds an element to the end of the array. The includes() method checks whether a particular value is present.

Question: Can you modify the contents of a const array in TypeScript?

Notice that the array is declared with const, but its contents can still be modified. The variable binding cannot be reassigned to a different array, but methods such as push() can change the existing array.

8. For Loops in TypeScript

A loop repeats a block of code. In test automation, loops are useful when the same operation needs to be performed for several values.

Question: When is a traditional for loop useful in test automation?

Traditional for loop

const products: string[] = [
    'Sauce Labs Backpack',
    'Sauce Labs Bike Light',
    'Sauce Labs Bolt T-Shirt'
];
// Copyright © 2026 https://inderpsingh.blogspot.com/
for (let i = 0; i < products.length; i++) {
    console.log(products[i]);
}

The loop starts at index zero and continues while i is less than the array length. After each iteration, i++ increments the index.

This approach is useful when you need both the array element and its index.

Question: When should you use a for...of loop instead of a traditional for loop?

For...of loop

The for...of loop is often more readable when you need to process each value without using its index.

for (const productName of testData.products) {
    await inventory.addItemToCart(productName);
}

This example assumes that testData.products is an array of product names and that inventory is a Page Object exposing the addItemToCart() method.

During each iteration, productName contains the current product name. The awaited method call completes before the loop proceeds to the next iteration.

Question: What is the difference between break and continue in a loop?

Break and continue statements

The break statement exits a loop, while continue skips the remainder of the current iteration and moves to the next one.

for (const productName of products) {
    if (productName === 'Sauce Labs Backpack') {
        continue;
    }

    if (productName === 'Sauce Labs Bike Light') {
        break;
    }

    console.log(productName);
}

In this example, the backpack is skipped. When the loop reaches the bike light, it exits before printing that product.

Use these statements carefully in automation. An early exit can prevent later products or validations from being processed, so the behavior should match the test requirement.

9. Comparison Operators

Question: What are comparison operators, and which ones are commonly used in TypeScript?

Comparison operators evaluate relationships between values and return a Boolean result.

  • ===: Strict equality.
  • !==: Strict inequality.
  • >: Greater than.
  • <: Less than.
  • >=: Greater than or equal to.
  • <=: Less than or equal to.

For example, a test can use a comparison to check whether a product price exceeds a defined threshold or whether an API response status falls within an expected range.

10. Functions, Parameters, and Return Types

Question: What is a function in TypeScript, and what do parameter and return type annotations specify?

A function packages a reusable operation. TypeScript lets you specify parameter types and return types, which helps clarify how the function should be used.

Example: Building an expected inventory URL

function getExpectedInventoryUrl(baseUrl: string): string {
    return `${baseUrl.replace(/\/$/, '')}/inventory.html`;
}

const expectedUrl: string =
    getExpectedInventoryUrl('https://www.saucedemo.com/');

console.log(expectedUrl);

The parameter baseUrl must be a string, and the function returns a string. The function removes a trailing slash before appending the inventory path.

This prevents an unnecessary double slash from appearing in the generated URL.

Note: To get free QA Test Automation guides, follow our Company page (2.9K followers) on LinkedIn.  

Example: A typed API helper

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

async function getPetName(
    request: APIRequestContext,
    petId: number
): Promise<string> {
    const response = await request.get(
        `https://petstore.swagger.io/v2/pet/${petId}`
    );

    if (!response.ok()) {
        throw new Error(
            `PetStore returned HTTP ${response.status()}`
        );
    }

    const pet: unknown = await response.json();

    if (
        typeof pet !== 'object' ||
        pet === null ||
        !('name' in pet) ||
        typeof pet.name !== 'string'
    ) {
        throw new Error('The response does not contain a valid pet name');
    }

    return pet.name;
}

Question: What does Promise<string> indicate as the return type of an async function?

This function accepts a Playwright API request context and a numeric pet ID. It returns a Promise that resolves to a string when the request succeeds and the response contains a valid name.

Notice that the response body is initially treated as unknown. External JSON should be validated at runtime before the test relies on its structure. A TypeScript type annotation alone cannot guarantee that a server returned the expected data.

11. Arrow Functions and Callback Functions

Question: What is an arrow function, and what is a callback function?

Arrow functions provide a concise way to define functions. They are commonly used in array methods, event handlers, and Playwright callbacks.

Question: How does the Array.filter() method work with a callback function?

Example: Filtering product names

const products = [
    'Sauce Labs Backpack',
    'Sauce Labs Bike Light',
    'Sauce Labs Bolt T-Shirt'
];

const matchingProducts = products.filter(
    (name: string) => name.includes('Sauce Labs')
);

console.log(matchingProducts);

The callback passed to filter() runs for each array element. The method returns a new array containing the values that satisfy the condition.

Example: Evaluating an element in the browser

const headerText = await page
    .locator('.app_logo')
    .evaluate((element: Element) => element.textContent);

console.log(headerText);
// Copyright © 2026 https://inderpsingh.blogspot.com/

12. Object Types and Interfaces

Question: What is a TypeScript interface, and how can it define test data?

An object groups related properties into a single structure. An interface describes the expected shape of an object and helps TypeScript detect missing or incorrectly typed properties.

Example: Defining login test data

interface LoginTestData {
    username: string;
    password: string;
    expectedOutcome: 'success' | 'locked';
}

const standardUser: LoginTestData = {
    username: 'standard_user',
    password: 'secret_sauce',
    expectedOutcome: 'success'
};

const lockedUser: LoginTestData = {
    username: 'locked_out_user',
    password: 'secret_sauce',
    expectedOutcome: 'locked'
};

The interface requires three properties. The expectedOutcome property accepts only the declared values, success or locked.

This helps prevent mistakes such as accidentally assigning an unexpected outcome label to a test scenario.

Example: Defining a PetStore response interface

interface Pet {
    id: number;
    name: string;
    photoUrls: string[];
    status?: 'available' | 'pending' | 'sold';
}

const expectedPet: Pet = {
    id: 12345,
    name: 'Training Pet',
    photoUrls: [],
    status: 'available'
};

Question: What does the question mark mean on an optional interface property?

The question mark indicates that status is optional. The interface describes the expected structure, but it does not validate an actual API response at runtime.

13. Optional Parameters and Default Parameters

Question: What is the difference between an optional parameter and a default parameter?

Optional parameters allow a function to be called without providing every argument. Default parameters supply a value when an argument is omitted.

Example: Creating a reusable test name

function buildPetName(
    prefix: string,
    suffix: string = 'test'
): string {
    return `${prefix}-${suffix}`;
}

const firstName = buildPetName('session14-pet');
const secondName = buildPetName('session14-pet', 'api');

console.log(firstName);
console.log(secondName);

The first call uses the default suffix, while the second supplies a custom suffix.

Example: Using an optional parameter

function buildSearchUrl(
    baseUrl: string,
    status?: string
): string {
    if (status) {
        return `${baseUrl}/pet/findByStatus?status=${encodeURIComponent(status)}`;
    }

    return `${baseUrl}/pet/findByStatus`;
}

The status parameter can be omitted. If a value is supplied, the function includes it in the URL.

For real API testing, prefer Playwright's request options and query-parameter support where appropriate. This helps avoid manually constructing query strings and makes parameter handling clearer.

14. Union Types and Type Narrowing

Question: What are union types and type narrowing in TypeScript?

A union type allows a variable or parameter to hold one of several specified types. Type narrowing uses runtime checks to determine which type applies in a particular branch of code.

Example: Representing API outcomes

type ApiOutcome = 'success' | 'not-found' | 'server-error';

function describeOutcome(outcome: ApiOutcome): string {
    switch (outcome) {
        case 'success':
            return 'The request succeeded';

        case 'not-found':
            return 'The resource was not found';

        case 'server-error':
            return 'The server reported an error';
    }
}

The ApiOutcome type prevents arbitrary strings from being passed to the function during normal TypeScript type checking.

Example: Validating a PetStore response

const response = await request.get(
    'https://petstore.swagger.io/v2/pet/12345'
);

if (response.status() === 200) {
    const body: unknown = await response.json();

    if (
        typeof body === 'object' &&
        body !== null &&
        'name' in body &&
        typeof body.name === 'string'
    ) {
        expect(body.name.length).toBeGreaterThan(0);
    } else {
        throw new Error(
            'Response does not contain a valid pet name'
        );
    }
} else {
    throw new Error(
        `Unexpected HTTP status: ${response.status()}`
    );
}

Question: Why should an API response be checked at runtime even when a TypeScript project uses types?

The code treats the response body as unknown until it confirms that the body is a non-null object with a string-valued name property.

The PetStore endpoint is a public example service, so the illustrative pet ID may not exist when you run the test. Use a known test record or create the required record as part of an isolated test setup.

15. Type Aliases and Readonly Properties

Question: What is a type alias, and how can it improve readability?

A type alias gives a reusable name to a type. A readonly property prevents reassignment of that property in code checked by TypeScript.

Example: Defining reusable product types

type ProductName = string;

type ProductStatus = 'available' | 'unavailable';

interface ProductCheck {
    readonly name: ProductName;
    status: ProductStatus;
}

const productCheck: ProductCheck = {
    name: 'Sauce Labs Backpack',
    status: 'available'
};

productCheck.status = 'unavailable';

// TypeScript error:
// productCheck.name = 'Sauce Labs Bike Light';

ProductName is an alias for the string type. ProductStatus restricts the allowed status values. The name property cannot be reassigned in code that respects TypeScript's type checks.

Question: Does readonly make an object immutable at runtime?

Readonly is a compile-time restriction, not a runtime security boundary. It does not automatically freeze the object or make nested arrays and objects immutable.

16. Object Destructuring and Spread Syntax

Question: What are object destructuring and spread syntax in TypeScript?

Destructuring extracts properties from an object into local variables. Spread syntax copies enumerable properties into a new object or combines collections. Both are useful when preparing test data and API request payloads.

Example: Extracting PetStore data

const pet = {
    id: 12345,
    name: 'Training Pet',
    status: 'available'
};

const { id, name, status } = pet;

console.log(id);
console.log(name);
console.log(status);

Example: Updating a request payload

const originalPet = {
    id: 12345,
    name: 'Training Pet',
    photoUrls: [],
    status: 'available'
};
// Copyright © 2026 https://inderpsingh.blogspot.com/
const updatedPet = {
    ...originalPet,
    name: 'Updated Training Pet'
};

console.log(updatedPet);

The spread operator copies the original object's properties. The later name property overrides the original value.

17. Error Handling with Try and Catch

Question: How can try and catch be used to handle errors in Playwright tests?

Browser actions and API requests can fail for many reasons, including timeouts, network problems, unexpected responses, or application errors. A try/catch block allows you to add context to errors or perform suitable cleanup.

Example: Handling a PetStore request failure

try {
    const response = await request.get(
        'https://petstore.swagger.io/v2/pet/12345'
    );

    expect(response.status()).toBe(200);

    const pet = await response.json();

    expect(pet).toHaveProperty('id');
} catch (error: unknown) {
    const message =
        error instanceof Error ? error.message : String(error);

    throw new Error(
        `PetStore validation failed: ${message}`
    );
}

Question: Why should a test usually rethrow an assertion failure rather than silently continue?

This example adds context to the error and rethrows it so the test still fails. An assertion failure inside the try block is also caught and rethrown.

18. Useful Array Methods for Test Automation

Question: Which common TypeScript array methods can help process test data?

In addition to loops, TypeScript provides array methods that make data processing more readable. These methods are useful when preparing test inputs or checking collections of values.

Question: What does the map() array method return?

Map: Transform each element

const products = [
    'Sauce Labs Backpack',
    'Sauce Labs Bike Light'
];

const normalizedProducts = products.map(
    (product: string) => product.toLowerCase()
);

The map() method creates a new array containing the transformed values.

Question: What does the filter() array method return?

Filter: Select matching elements

const statuses = ['available', 'sold', 'available'];

const availableStatuses = statuses.filter(
    (status: string) => status === 'available'
);

The filter() method returns a new array containing only the values that satisfy the condition.

Question: What does the find() array method return when there is no match?

Find: Return the first matching element

const petIds = [101, 202, 303];

const targetPet = petIds.find(
    (id: number) => id === 202
);

The find() method returns the first matching element or undefined if no match is found.

Question: When does the every() array method return true?

Every: Check whether all elements match

const responseStatuses = [200, 200, 200];

const allSuccessful = responseStatuses.every(
    (status: number) => status >= 200 && status < 300
);

The every() method returns true only when every element satisfies the condition.

Question: When does the some() array method return true?

Some: Check whether at least one element matches

const responseStatuses = [200, 404, 200];

const containsNotFound = responseStatuses.some(
    (status: number) => status === 404
);

The some() method returns true when at least one element satisfies the condition.

These methods are useful for processing collected data. For live UI validation, prefer Playwright's retrying assertions when checking elements that may change over time.

19. Data-Driven Login Testing

You're welcome to connect with me on LinkedIn at Inder P Singh (15K Followers). Now, let's combine interfaces, arrays, loops, conditional statements, asynchronous operations, and Playwright assertions in one example.

Question: What is data-driven testing, and how does this example use it for login scenarios?

The following code defines two login scenarios and verifies the expected result for each one.

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

interface LoginScenario {
    username: string;
    password: string;
    expectedOutcome: 'success' | 'locked';
}

const loginScenarios: LoginScenario[] = [
    {
        username: 'standard_user',
        password: 'secret_sauce',
        expectedOutcome: 'success'
    },
    {
        username: 'locked_out_user',
        password: 'secret_sauce',
        expectedOutcome: 'locked'
    }
];

test('validate login scenarios', async ({ page }) => {
    for (const scenario of loginScenarios) {
        await page.goto('https://www.saucedemo.com/');

        await page.locator('[data-test="username"]')
            .fill(scenario.username);

        await page.locator('[data-test="password"]')
            .fill(scenario.password);

        await page.locator('[data-test="login-button"]')
            .click();

        if (scenario.expectedOutcome === 'locked') {
            await expect(
                page.locator('[data-test="error"]')
            ).toContainText(
                'Sorry, this user has been locked out'
            );
        } else {
            await expect(page).toHaveURL(/inventory.html/);
        }
    }
});

This example explains how typed test data and control flow can work together. Each scenario contains a username, password, and expected outcome. The loop executes the login workflow, and the conditional selects the appropriate assertion.

Question: Why might separate Playwright test cases be preferable to looping through multiple scenarios in one test?

For a production test suite, separate Playwright test cases or a Playwright test-data pattern are usually preferable when each scenario needs independent reporting and failure isolation. The example above is primarily intended to demonstrate TypeScript concepts.

20. PetStore API Response Validation

Question: How can a Playwright API test validate the structure and values of a JSON response?

TypeScript is also useful for API automation. Interfaces can describe the expected response structure, while runtime checks help verify that the actual response matches that structure.

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

test('validate PetStore API response', async ({ request }) => {
    const response = await request.get(
        'https://petstore.swagger.io/v2/pet/12345'
    );

    expect(response.status()).toBe(200);

    const body: unknown = await response.json();

    if (
        typeof body !== 'object' ||
        body === null ||
        !('id' in body) ||
        typeof body.id !== 'number' ||
        !('name' in body) ||
        typeof body.name !== 'string' ||
        !('photoUrls' in body) ||
        !Array.isArray(body.photoUrls)
    ) {
        throw new Error(
            'PetStore response does not match the expected structure'
        );
    }

    expect(body.id).toBe(12345);
    expect(body.name.length).toBeGreaterThan(0);
});

The response body is treated as unknown until the code checks its structure. The test then validates the identifier and name.

21. Quick TypeScript Reference for Test Automation

Question: Which TypeScript syntax patterns are useful to remember for Playwright test automation?

Use this quick reference when revising the concepts covered in the examples.

Variables

const username: string = 'standard_user';
let attemptCount: number = 0;

Functions

function calculateTotal(price: number, quantity: number): number {
    return price * quantity;
}

Arrow functions

const isSuccessful = (status: number): boolean =>
    status >= 200 && status < 300;

Interfaces

interface Pet {
    id: number;
    name: string;
    status?: string;
}

Union types

type TestStatus = 'passed' | 'failed' | 'skipped';

Optional parameters

function getEnvironment(
    name: string,
    fallback?: string
): string {
    return fallback ?? name;
}

Destructuring

const { id, name } = {
    id: 123,
    name: 'Training Pet'
};

Spread syntax

const updatedPet = {
    ...originalPet,
    name: 'Updated Pet'
};

Error handling

try {
    const response = await request.get(
        'https://petstore.swagger.io/v2/pet/12345'
    );

    expect(response.status()).toBe(200);
} catch (error: unknown) {
    const message =
        error instanceof Error ? error.message : String(error);

    throw new Error(`Request failed: ${message}`);
}

Array operations

products.map(product => product.toLowerCase());

products.filter(product => product.includes('Sauce Labs'));

products.find(product => product === 'Sauce Labs Backpack');

responseStatuses.every(status => status === 200);

responseStatuses.some(status => status >= 400);

Conclusion

Question: Which TypeScript concepts are especially useful for building maintainable Playwright automation frameworks?

TypeScript provides useful building blocks for creating maintainable Playwright automation frameworks. Variables and type annotations make values easier to understand. Classes and interfaces help organize reusable components and test data. Functions reduce duplication, while arrays, loops, and conditional statements make data-driven testing easier to implement.

Async and await are particularly important because Playwright browser actions and API requests are asynchronous. Runtime assertions and validation are equally important because TypeScript types alone cannot guarantee that the application or an external API returned the expected result.

Start by practicing these examples, then apply the concepts to your own Page Objects, fixtures, test data, and API helpers. The goal is not to memorize syntax. It is to understand how each feature helps you write automation that is easier to read, debug, and maintain.

For further reference, visit the official TypeScript documentation and the official Playwright documentation.

If you want any of the following, send a message using the Contact Us (right pane) or message Inder P Singh (19 years' experience in Test Automation and QA) in LinkedIn at https://www.linkedin.com/in/inderpsingh/

  • Production-oriented Playwright TypeScript automation templates with playbooks
  • Runnnable Playwright TypeScript projects for your portfolio
  • Deep-dive hands-on Playwright TypeScript Training
  • TypeScript For Test Automation Resume Updates