Assertions are one of the most important concepts in Playwright test automation. They verify whether the application behaves as expected after performing an action. Without assertions, your automation script simply performs actions without validating the results.
Playwright provides a powerful assertion library built on top of expect(), which automatically waits for conditions to become true before failing the test. This feature makes Playwright tests much more reliable compared to traditional automation frameworks.
In this article, you’ll learn everything about Playwright assertions, including different assertion types, best practices, and practical examples using TypeScript.
What are Assertions?
Assertions verify the expected state of your application.
For example, after clicking the Login button, you may want to verify:
User is redirected to Dashboard
Welcome message is displayed
Logout button is visible
Shopping cart contains 3 products
If the expected condition is not met, the test fails.
Example:
expect(await page.title()).toBe("Dashboard");
Why Playwright Assertions are Powerful
Unlike traditional assertions, Playwright assertions:
Prefer Playwright locator assertions (toBeVisible, toHaveText, etc.) over manual value checks because they automatically wait for the expected condition.
Avoid using waitForTimeout() before assertions. Let Playwright’s built-in retry mechanism handle synchronization.
Use descriptive locators (getByRole, getByLabel, getByTestId) instead of fragile CSS or XPath selectors whenever possible.
Use expect.soft() when you want to collect multiple verification failures in a single test execution.
Keep assertions focused on one expected behavior to make failures easier to understand.
Add meaningful custom messages for business-critical validations.
Use regular expressions with toHaveURL() and toHaveText() when parts of the value are dynamic.
For visual testing, use screenshot assertions only for stable UI components to reduce flaky results.
Set assertion-specific timeouts only when an element legitimately requires more time to appear.
Playwright assertions are a core part of building stable and maintainable automated tests. Their automatic waiting, intelligent retries, and rich set of locator-specific assertions eliminate much of the flakiness found in traditional UI automation frameworks.
By mastering value assertions, locator assertions, page assertions, API assertions, soft assertions, polling, and visual assertions, you can create robust end-to-end tests that are easier to read, debug, and maintain. Adopting Playwright’s built-in assertion methods instead of manual waits or custom validation logic will result in faster, more reliable, and more professional automation suites.
Locators are one of the most important concepts in Playwright. A locator is used to find and interact with elements on a web page. Unlike traditional Selenium locators, Playwright locators are smart, reliable, auto-waiting, and resilient.
Playwright automatically waits for elements to become:
Visible
Stable
Enabled
Ready for interaction
This significantly reduces flaky test cases.
What is a Locator?
A locator is an object that identifies one or more elements on a web page.
Example:
const username = page.locator('#username');
The locator does not immediately search for the element.
Instead, Playwright waits until the action is performed.
Playwright locators are designed to create reliable, readable, and maintainable UI automation tests. Instead of relying on fragile selectors, Playwright encourages the use of accessibility-aware locators such as getByRole(), getByLabel(), and getByTestId(). By combining locator chaining, filtering, built-in assertions, and auto-waiting, you can build test suites that are less flaky and easier to maintain over time.
Mastering Playwright locators is a foundational skill for any automation engineer and is essential for developing scalable Playwright frameworks using TypeScript.
Modern organizations rarely execute Playwright tests directly on developers’ machines. Instead, they package the automation framework into Docker containers and execute them in Kubernetes clusters for scalability, consistency, and faster execution.
This chapter explains how to run Playwright in Docker and Kubernetes using industry best practices.
Table of Contents
Why Docker?
Why Kubernetes?
Docker Architecture
Installing Docker
Running Playwright in Docker
Creating Dockerfile
Creating .dockerignore
Docker Commands
Docker Compose
Running Playwright Reports
Kubernetes Architecture
Running Playwright on Kubernetes
Kubernetes Deployment
ConfigMap
Secret Management
Persistent Volumes
Best Practices
Interview Questions
What is Docker?
Docker is a containerization platform that packages an application with all of its dependencies.
Configure readiness and liveness probes when appropriate.
Set CPU and memory requests/limits.
Store reports outside Pods.
Scale horizontally instead of creating oversized Pods.
Use namespaces to separate environments such as Dev, QA, and UAT.
Docker vs Kubernetes
Docker
Kubernetes
Builds and runs containers
Orchestrates containers
Runs on a single machine
Manages clusters
Manual scaling
Automatic scaling
Manual restart
Self-healing
Simple deployment
Enterprise deployment
Good for local development
Best for production environments
Common Interview Questions
1. Why use Docker with Playwright?
Answer: Docker provides a consistent execution environment across local machines and CI/CD systems, eliminating dependency and browser version differences.
2. Why use the official Playwright Docker image?
Answer: It already contains compatible versions of Node.js, Playwright, browsers, and required Linux dependencies, reducing setup effort and compatibility issues.
3. What is the difference between a Docker image and a container?
Answer: A Docker image is an immutable blueprint containing the application and its dependencies. A container is a running instance of that image.
4. Why use Kubernetes for Playwright?
Answer: Kubernetes automates deployment, scaling, recovery, and management of Playwright containers, making it suitable for large-scale parallel test execution.
5. What is a Pod?
Answer: A Pod is the smallest deployable unit in Kubernetes. It contains one or more containers that share networking and storage resources.
6. How do you securely manage credentials in Kubernetes?
Answer: Use Kubernetes Secrets (or an enterprise secrets manager) and inject them into Pods as environment variables or mounted files instead of storing them in source code or Docker images.
7. How would you execute 5,000 Playwright tests quickly?
Answer: Split tests into logical suites, run them in parallel across multiple Playwright workers and Kubernetes Pods, reuse authenticated sessions with storageState, use API-based test data setup where possible, and collect reports from shared storage.
8. What challenges have you seen when running Playwright in containers?
Answer: Common challenges include browser resource consumption, report persistence, secure secret management, parallel test data collisions, and ensuring enough CPU and memory for stable execution. These are addressed through proper container configuration, persistent storage, isolated test data, and Kubernetes resource management.
SOLID is a set of five object-oriented design principles introduced by Robert C. Martin (Uncle Bob). These principles help developers build software that is:
Easy to maintain
Easy to extend
Highly reusable
Loosely coupled
Easy to test
In enterprise Playwright frameworks, following SOLID principles results in cleaner Page Objects, reusable utilities, scalable workflows, and better test automation architecture.
Why SOLID is Important in Automation Frameworks
Without SOLID principles, frameworks often become:
It prevents Page Objects from becoming large and difficult to maintain. By separating responsibilities into page objects, utilities, workflows, and services, the framework becomes cleaner, reusable, and easier to extend.
O — Open Closed Principle (OCP)
Definition
Software entities should be open for extension but closed for modification.
A browser launcher should support new browsers without changing existing code. Using Strategy Pattern, each browser has its own implementation, allowing new browsers to be added by creating new strategy classes rather than modifying the launcher.
L — Liskov Substitution Principle (LSP)
Definition
A derived class should be replaceable with its base class without breaking the application.
Example
Suppose
BasePage
contains
open()
waitForPage()
verifyTitle()
Now
LoginPage
DashboardPage
CheckoutPage
extend BasePage.
Any of them should work wherever a BasePage is expected.
Good Example
BasePage
↓
LoginPage
↓
DashboardPage
↓
CartPage
Each subclass honors the behavior defined by the base class.
Bad Example
Suppose BasePage defines
openPage()
but CheckoutPage throws an exception because it cannot open itself.
That violates LSP.
Benefits
✔ Better inheritance
✔ Predictable behavior
✔ Easier maintenance
Interview Question
How does LSP help automation?
Answer
It ensures that all page objects derived from a common base behave consistently. Shared framework code can work with any page object without requiring special handling.
I — Interface Segregation Principle (ISP)
Definition
Clients should not be forced to depend on interfaces they don’t use.
Every implementing class must define unnecessary methods.
Better Example
Separate interfaces.
ExcelReader
↓
readExcel()
ScreenshotService
↓
takeScreenshot()
FileUploader
↓
upload()
Benefits
✔ Small interfaces
✔ Easier implementation
✔ Better readability
Interview Question
Why is ISP useful in Playwright?
Answer
It avoids creating large interfaces that force unrelated implementations. Separate interfaces for reporting, screenshots, file handling, and data readers keep the framework modular and easier to maintain.
D — Dependency Inversion Principle (DIP)
Definition
High-level modules should not depend on low-level modules.
Both should depend on abstractions.
Bad Example
class LoginWorkflow{
private login=new LoginPage(page);
}
Strong coupling.
Better Example
Inject dependency.
constructor(private loginPage: LoginPage){
}
Now
LoginWorkflow
doesn’t create LoginPage.
Someone else provides it.
Architecture
Test
↓
Fixture
↓
Workflow
↓
Page Object
Each layer receives dependencies instead of creating them.
Playwright Example
Playwright Fixtures naturally support Dependency Injection.
Instead of
const page=new LoginPage(browserPage);
Fixtures inject
loginPage
directly into the test.
Benefits
✔ Loose coupling
✔ Easy testing
✔ Easy mocking
✔ Better scalability
Interview Question
How does Playwright support Dependency Injection?
Answer
Playwright fixtures inject dependencies such as browser instances, pages, authenticated sessions, and page objects into test functions. This reduces object creation inside tests and promotes loose coupling.
Move business flows to a separate Workflow (Facade) layer.
❌ Creating one huge Utility class
Split it into focused utilities:
Logger
DateUtility
JsonUtility
ExcelUtility
ScreenshotUtility
❌ Hardcoding object creation
Avoid:
const loginPage = new LoginPage(page);
Prefer dependency injection through Playwright fixtures or a factory.
❌ Large BasePage classes
Keep BasePage limited to truly common functionality such as navigation, waiting, or shared helpers. Don’t force unrelated pages to inherit unnecessary behavior.
❌ Large interfaces
Create small, purpose-specific interfaces rather than one interface containing dozens of unrelated methods.
Senior Playwright Interview Questions
1. What are SOLID principles?
Answer
SOLID is a set of five object-oriented design principles that improve maintainability, extensibility, reusability, and scalability. They help reduce coupling and encourage clean architecture.
2. Which SOLID principle is most important in automation?
Answer
All five are valuable, but Single Responsibility Principle (SRP) is often the most impactful because it prevents oversized Page Objects and encourages separation of concerns across pages, workflows, utilities, and services.
3. How does Playwright support Dependency Inversion?
Answer
Playwright fixtures provide dependency injection by supplying browser instances, contexts, pages, and custom page objects to tests. Tests depend on abstractions provided by fixtures instead of creating concrete objects themselves.
4. How do SOLID principles improve a Playwright framework?
Answer
They make the framework modular, reusable, easier to extend, and simpler to maintain. New functionality can often be added by introducing new classes rather than modifying existing ones, reducing the risk of breaking stable automation.
5. How do SOLID principles relate to design patterns?
Answer
Design patterns are practical implementations of SOLID ideas. For example:
SRP → Page Object Model, Workflow layer
OCP → Strategy Pattern
LSP → Base Page inheritance
ISP → Focused interfaces
DIP → Fixtures and Dependency Injection
Using SOLID together with patterns like Factory, Builder, Strategy, and Facade results in an enterprise-grade Playwright framework that is easier to scale and maintain over time.
As Playwright automation frameworks grow, applying design patterns helps improve maintainability, scalability, reusability, and test readability. These patterns are commonly discussed in interviews for Senior SDET, Automation Architect, and QA Lead roles.
Why Use Design Patterns?
Without design patterns, automation frameworks often suffer from:
Duplicate code
Tight coupling
Difficult maintenance
Large Page Objects
Hardcoded logic
Poor scalability
Using design patterns helps create frameworks that are easier to extend and maintain.
1. Factory Pattern
What is Factory Pattern?
The Factory Pattern centralizes object creation instead of allowing tests to instantiate classes directly.
Instead of:
const loginPage = new LoginPage(page);
const dashboardPage = new DashboardPage(page);
const cartPage = new CartPage(page);
Creates LoginPage, CartPage, CheckoutPage, and OrderPage.
Builder Pattern
Creates customer profiles, shipping addresses, payment requests, and order payloads.
Strategy Pattern
Chooses:
Browser (Chromium, Firefox, WebKit)
Login method (UI, API, SSO)
Payment method (Credit Card, PayPal, UPI)
Report type (HTML, Allure)
Together, these patterns produce a framework that is easier to maintain, easier to extend, and capable of supporting large-scale automation projects with minimal changes to existing code.
Senior SDET Interview Questions
1. Which design patterns have you used in your Playwright framework?
Answer: I commonly use the Page Object Model, Factory Pattern for page object creation, Builder Pattern for test data and API payloads, Strategy Pattern for browser and authentication selection, Facade/Workflow Pattern for business processes, and Dependency Injection through Playwright fixtures.
2. Which design pattern is most useful in automation frameworks?
Answer: There isn’t a single best pattern. Page Object Model is foundational, Factory simplifies object creation, Builder improves test data management, Strategy removes conditional logic, and Workflow (Facade) keeps business flows reusable. The best choice depends on the problem being solved.
3. How do these patterns improve maintainability?
Answer: They separate responsibilities, reduce code duplication, isolate changes, improve readability, and make it easier to extend the framework without modifying existing test code. This aligns with SOLID principles and results in a more scalable automation architecture.
In this section, we’ll build a production-ready Playwright automation framework and explain how each folder contributes to the overall architecture. This is the type of framework commonly used in enterprise applications and discussed in senior SDET interviews.
Run smoke tests on all browsers and reserve full regression for the browsers required by your project.
Step 16: Continuous Integration Flow
Developer Commit
↓
Pull Request
↓
Code Review
↓
Build
↓
Install Dependencies
↓
Install Browsers
↓
Run Lint
↓
Run Unit Tests (if applicable)
↓
Run Smoke Automation
↓
Run Regression
↓
Generate Report
↓
Publish Artifacts
↓
Notify Team
Step 17: Pull Request Checklist
Before creating a PR:
Code builds successfully
All tests pass
ESLint passes
Prettier formatting applied
No hardcoded values
No static waits
No duplicate methods
Meaningful commit messages
Updated documentation (if required)
Step 18: Versioning Strategy
Example:
Version 1.0
↓
Version 1.1
↓
Version 1.2
↓
Version 2.0
Tag framework releases to simplify rollback and traceability.
Step19: Recommended NPM Scripts
Typical scripts include:
test
test:smoke
test:regression
test:headed
test:chrome
test:firefox
test:webkit
report
lint
format
These provide a consistent way to execute different suites.
Step 20: Enterprise Coding Guidelines
Follow these principles:
Single Responsibility Principle
Each class should have one responsibility.
Open/Closed Principle
Design classes so they can be extended without modifying existing behavior wherever practical.
DRY (Don’t Repeat Yourself)
Move repeated logic into reusable methods or workflows.
KISS (Keep It Simple, Stupid)
Prefer simple, readable solutions over unnecessary complexity.
YAGNI (You Aren’t Gonna Need It)
Don’t implement features before they are actually required.
Step 21: Enterprise Framework Maturity Model
Beginner Framework
Tests
Page Objects
Intermediate Framework
Fixtures
Utilities
Reporting
Environment support
Advanced Framework
Business workflows
API integration
Parallel execution
CI/CD
Authentication reuse
Robust logging
Cross-browser support
Enterprise Framework
Scalable architecture
Secure configuration management
API + UI hybrid testing
Containerized execution
Cloud execution
Comprehensive reporting
Test analytics
Quality gates in CI/CD
Senior Playwright Interview Questions & Answers
1. Why would you introduce a Workflow Layer?
Answer:
A workflow layer encapsulates complete business processes that span multiple pages. This keeps page objects focused on page interactions while making test cases shorter, more readable, and easier to maintain.
2. What is the difference between a Page Object and a Workflow?
Answer:
A Page Object models a single page by exposing its locators and actions.
A Workflow coordinates multiple page objects to accomplish a business process such as placing an order or completing user registration.
3. Why shouldn’t business logic be placed inside page objects?
Answer:
Business workflows often involve multiple pages. Keeping them in page objects creates oversized classes, increases coupling, and makes reuse difficult. Separating workflows improves maintainability and follows the Single Responsibility Principle.
4. How do you organize a framework for thousands of test cases?
Answer:
I organize it into layers (tests, workflows, page objects, utilities, API helpers, fixtures), group tests by feature, externalize configuration and test data, enable parallel execution, use authentication reuse, and integrate reporting and CI/CD.
5. How do you reduce execution time in Playwright?
Answer:
Execute tests in parallel.
Reuse authenticated sessions with storageState.
Create test data through APIs instead of the UI where appropriate.
Categorize suites into smoke and regression.
Avoid unnecessary browser launches and redundant setup.
Remove fixed waits.
6. How do you handle flaky tests?
Answer:
I investigate the root cause rather than relying on retries. Common improvements include using stable locators, waiting on application state instead of time, isolating test data, improving cleanup, and reviewing application synchronization issues.
7. What qualities define a production-ready Playwright framework?
Answer:
A production-ready framework has a clean layered architecture, reusable fixtures, focused page objects, workflow abstraction, secure configuration management, reliable reporting, logging, authentication reuse, CI/CD integration, parallel execution, cross-browser support, coding standards, and comprehensive
This guide explains how to create a production-ready Playwright Automation Framework using TypeScript while following industry standards. It also includes best practices, framework standards, folder structure, and interview questions.
Table of Contents
Introduction to Playwright
Prerequisites
Install Playwright
Create Project Structure
Configure Playwright
Create Test Data
Create Page Objects
Create Utility Classes
Create Base Framework
Write Test Cases
Execute Tests
Generate Reports
Logging
Screenshots & Videos
CI/CD Integration
Framework Standards
Coding Standards
Common Mistakes
Automation Project Interview Questions
Step 1: Understand Playwright
Playwright is Microsoft’s modern end-to-end automation framework that supports:
Chromium
Firefox
WebKit
Mobile Browsers
Supports
TypeScript
JavaScript
Python
Java
.NET
Step 2: Install Node.js
Verify installation
node -v
npm -v
Step 3: Create Project
mkdir PlaywrightFramework
cd PlaywrightFramework
npm init -y
Answer: POM separates test logic from page interaction logic, making the framework easier to maintain, reusable, and scalable. Changes to page locators are usually made in one place instead of every test.
2. Why do you use fixtures?
Answer: Fixtures manage reusable setup and teardown logic, such as browser creation, authenticated sessions, and test data initialization. They reduce duplication and improve test consistency.
3. Why should locators not be written directly in test files?
Answer: Keeping locators in page objects or dedicated locator files centralizes maintenance. When the UI changes, updates are required in only one place.
4. Why separate test data from test scripts?
Answer: External test data (JSON, CSV, Excel, etc.) makes tests reusable, supports multiple datasets, and allows non-developers to update test inputs without changing code.
5. Why avoid waitForTimeout()?
Answer: Fixed waits slow down test execution and can make tests flaky. Playwright provides automatic waiting and assertion-based waiting that are generally more reliable.
6. What is the purpose of playwright.config.ts?
Answer: It centralizes framework configuration such as browser settings, retries, reporters, timeouts, projects, base URL, and execution behavior.
7. Why use baseURL in Playwright?
Answer: Using a baseURL allows tests to navigate with relative paths, making it easier to switch environments without changing test code.
8. How do you execute tests in parallel?
Answer: Playwright supports parallel execution through workers and projects. Independent tests can run simultaneously to reduce execution time.
9. Why use traces, videos, and screenshots?
Answer: They provide diagnostic information for failed tests, making it easier to identify the cause of failures without rerunning the tests.
10. How do you handle different environments?
Answer: Store environment-specific values (such as URLs and credentials) in environment files or configuration, and load the required configuration based on the execution environment.
11. How do you make Playwright tests stable?
Answer: By using resilient locators, relying on Playwright’s built-in waiting mechanisms, writing independent tests, avoiding fixed delays, and using proper assertions.
12. How do you organize a large Playwright framework?
Answer: A scalable framework separates responsibilities into folders such as tests, pages, fixtures, utils, test-data, reports, and config, following the Single Responsibility Principle.
13. What is the difference between beforeEach and fixtures?
Answer: beforeEach is useful for simple per-test setup, while fixtures provide dependency injection, composability, type safety, and reusable setup/teardown across the framework.
14. How do you manage authentication efficiently?
Answer: Use Playwright’s storageState to save an authenticated session after login and reuse it across tests, avoiding repeated login steps.
15. What standards do you follow while building an automation framework?
Answer:
Page Object Model
Independent test cases
Externalized test data
Centralized configuration
Reusable fixtures and utilities
Meaningful logging
Robust reporting
Version control best practices
CI/CD integration
Consistent coding standards
Minimal code duplication (DRY)
Clear folder structure
Proper assertions and error handling
Final Framework Checklist
Before considering your Playwright framework production-ready, ensure it includes:
✅ Well-defined folder structure
✅ Page Object Model
✅ Custom fixtures
✅ External test data
✅ Environment-specific configuration
✅ Reusable utility classes
✅ Centralized configuration
✅ HTML and Allure reporting
✅ Automatic screenshots, videos, and traces on failure
✅ Logging support
✅ Parallel execution
✅ Cross-browser testing
✅ Authentication using storageState
✅ GitHub Actions or other CI/CD integration
✅ Linting and code formatting (ESLint and Prettier)
✅ Meaningful test names and documentation
✅ Stable, independent, and maintainable test cases
The following practices are commonly followed in enterprise-level automation projects to build scalable, maintainable, and reliable Playwright frameworks.
Step 24: Test Design Standards
A good automation framework starts with well-designed test cases.
Follow AAA Pattern
Every test should follow the Arrange → Act → Assert pattern.
Arrange
↓
Launch Browser
Load Test Data
Act
↓
Perform User Actions
Assert
↓
Verify Expected Result
Example Structure
test('Verify user can login successfully', async ({ loginPage }) => {
// Arrange
const user = loginData.validUser;
// Act
await loginPage.login(user.username, user.password);
// Assert
await expect(loginPage.dashboardTitle).toBeVisible();
});
This section covers advanced topics used in real-world automation projects. These concepts are commonly discussed in interviews for 3–8 years of QA Automation Engineer / SDET roles.
Step 46: Custom Fixtures
What are Fixtures?
Fixtures provide reusable setup and teardown logic that can be injected into tests. They help avoid duplicated initialization code and improve test maintainability.
Instead of writing:
Launch Browser
Create Context
Open Page
Login
Run Test
inside every test, you create fixtures once and reuse them.
INFO Browser launched
INFO Login page opened
INFO Username entered
INFO Password entered
INFO Login successful
INFO Dashboard verified
INFO Test passed
Avoid excessive logging of trivial actions.
Step 62: Error Handling
When a test fails:
Capture:
Screenshot
Video (if enabled)
Trace
Browser console logs (if helpful)
Network logs (for debugging API issues)
Error message
Stack trace
This significantly reduces debugging time.
Step 63: Framework Scalability
A scalable framework should support:
Hundreds or thousands of tests
Multiple applications
Multiple browsers
Multiple environments
Multiple user roles
Parallel execution
CI/CD integration
Without major architectural changes.
Step 64: Maintainability Checklist
A maintainable framework should:
Minimize duplicated code
Use reusable components
Centralize configuration
Use clear naming conventions
Keep page objects focused
Keep utilities generic
Use meaningful comments only where needed
Step 65: Enterprise Framework Layers
Test Layer
│
▼
Fixture Layer
│
▼
Business Workflow Layer
│
▼
Page Object Layer
│
▼
Utility Layer
│
▼
Playwright Framework Layer
│
▼
Browser Engine
│
▼
Application Under Test
The optional Business Workflow Layer contains reusable business processes (for example, “placeOrder” or “createCustomer”) that span multiple page objects while keeping page objects focused on individual pages.
Step 66: Enterprise Automation Checklist
Before releasing an automation framework, verify:
✅ Clear folder structure
✅ Page Object Model implemented
✅ Custom fixtures
✅ Externalized test data
✅ Environment-specific configuration
✅ Authentication reuse with storageState
✅ Robust logging
✅ HTML and/or Allure reporting
✅ Screenshots on failure
✅ Trace collection on failure
✅ Video retention on failure (optional)
✅ Parallel execution support
✅ Cross-browser execution
✅ API integration where appropriate
✅ Linting (ESLint)
✅ Code formatting (Prettier)
✅ GitHub Actions or other CI/CD integration
✅ Documentation (README.md)
✅ Stable, independent test cases
Advanced Playwright Interview Questions & Answers
1. What is the purpose of custom fixtures in Playwright?
Answer: Custom fixtures encapsulate reusable setup and teardown logic, provide dependency injection, and reduce duplication. They simplify test code by supplying ready-to-use objects such as authenticated pages or page objects.
2. What is storageState?
Answer: storageState stores browser authentication information, including cookies and local storage. After logging in once, the saved state can be reused across tests, eliminating repeated login steps and improving execution speed.
3. Why use Browser Context instead of multiple Browser instances?
Answer: Browser contexts are lightweight, isolated sessions within the same browser process. They consume fewer resources while providing separate cookies, storage, and cache, making them ideal for multi-user testing.
4. What are the advantages of Playwright over Selenium?
Answer:
Built-in auto-waiting
Native support for Chromium, Firefox, and WebKit
Fast parallel execution
Built-in tracing, screenshots, and video
Network interception
Reliable locator APIs
Multiple isolated browser contexts
Rich TypeScript support
5. How do you make Playwright tests less flaky?
Answer:
Use stable locators (getByRole, getByTestId, etc.)
Avoid fixed waits
Rely on Playwright’s auto-waiting and assertions
Keep tests independent
Use isolated test data
Retry only when appropriate
Capture traces and screenshots for debugging
6. What is the difference between a Browser, Browser Context, and Page?
Answer:
Browser: The browser engine instance.
Browser Context: An isolated browser session with its own cookies and storage.
Page: A single browser tab within a context.
7. Why should test cases be independent?
Answer: Independent tests can run in any order, execute safely in parallel, and are easier to debug because failures are isolated to a single scenario.
8. How would you design a Playwright framework for a large enterprise application?
Answer: I would use a layered architecture with Page Object Model, custom fixtures, reusable business workflows, externalized test data, environment-based configuration, authentication reuse via storageState, centralized logging and reporting, parallel execution, CI/CD integration, and clear coding standards.
Description: Write a JavaScript program to create a new string using the first 2 and last 2 characters of a given string. If the string length is less than 2, return an empty string.
Input:"JavaScript"
Expected Output:"Japt"
2. Find the Length of the Longest String in an Array
Description: Write a JavaScript program to find the length of the longest string from an array of strings.
Input:
["Java", "Programming", "Code"]
Expected Output:
11
3. Repeat the Last Two Characters Four Times
Description: Write a JavaScript program to create a string made of four copies of the last two characters.
Input:"Coding"
Expected Output:
ngngngng
4. Reverse a String if Its Length is a Multiple of 4
Description: Reverse the string only if its length is divisible by 4.
Input:"Code"
Expected Output:
edoC
5. Count Occurrences of a Substring
Description: Count how many times a substring appears inside a string.
Input:
String: "banana"
Substring: "an"
Expected Output:
2
6. Check Whether a Character is a Vowel or Consonant
Description: Determine whether a given alphabet is a vowel or consonant.
Input:"e"
Expected Output:
Vowel
7. Find the Longest and Shortest Word
Description: Find the longest and shortest words in a sentence.
Input:
"I love learning JavaScript"
Expected Output:
Longest: JavaScript
Shortest: I
8. Find the Most Frequently Repeated Character
Description: Find the character with the highest frequency.
Input:"programming"
Expected Output:
g
9. Calculate String Length Without Using length Property
Description: Find the length of a string using loop logic only.
Input:"JavaScript"
Expected Output:
10
10. Replace Every Second Occurrence of a Character with ‘$’
Description: Replace every second occurrence of each repeated character with the $ symbol.
Input:"Programming"
Expected Output:
Prog$am$in$
11. Swap the First and Last Character
Description: Exchange the first and last characters of the string.
Input:"JavaScript"
Expected Output:
tavaScripJ
12. Swap the First and Last Character of Every Word
Description: Exchange the first and last character of each word in a sentence.
Input:
"Online Learning"
Expected Output:
enliOn gearninL
13. Count Vowels in Each Word
Description: Count vowels present in every word and display the result as an object.
Input:
"We are learning JavaScript"
Expected Output:
{
We:1,
are:2,
learning:3,
JavaScript:3
}
14. Repeat Vowels Three Times and Consonants Twice
Description: Repeat every vowel three times and every consonant twice.
Input:"Code"
Expected Output:
CCooodee
15. Check Whether a String is a Palindrome
Description: Check whether the given string reads the same forwards and backwards.
Input:"madam"
Expected Output:
Palindrome
16. Reverse the Entire String
Description: Reverse all characters of the string.
Input:"JavaScript"
Expected Output:
tpircSavaJ
17. Calculate String Length
Description: Find the total number of characters in the string.
Input:"Programming"
Expected Output:
11
18. Count Frequency of Every Character
Description: Count the occurrences of each character.
Input:"hello"
Expected Output:
{
h:1,
e:1,
l:2,
o:1
}
19. Combine Two Strings
Description: Join two strings together.
Input:
"Hello"
"World"
Expected Output:
HelloWorld
20. Print Characters at Even Positions
Description: Display characters at even index positions.
Input:"JavaScript"
Expected Output:
JvSrp
21. Check Whether the String Contains Numbers
Description: Determine whether the string contains any numeric digit.
Input:"Code123"
Expected Output:
Contains Number
22. Count Total Vowels
Description: Count all vowels present in the string.
Input:"I love JavaScript"
Expected Output:
6
23. Count Total Consonants
Description: Count all consonants present in the string.
Input:"JavaScript"
Expected Output:
7
24. Print Characters at Odd Positions
Description: Display characters at odd index positions.
Input:"abcdefg"
Expected Output:
bdf
25. Remove Duplicate Characters
Description: Remove duplicate characters while preserving the first occurrence.
Input:"programming"
Expected Output:
progamin
26. Check Whether a String Contains Special Characters
Description: Write a JavaScript program to determine whether a given string contains any special characters.
Input:
"JavaScript@2025!"
Expected Output:
Given string contains special characters.
27. Exchange the First and Last Character of the Entire String
Description: Write a JavaScript program to swap the first and last character of the complete string.
Input:
"We are learning JavaScript"
Expected Output:
"ee are learning JavaScripW"
28. Convert All Characters to Uppercase
Description: Write a JavaScript program to convert all lowercase letters of a string into uppercase.
Input:
"I live in Pune"
Expected Output:
"I LIVE IN PUNE"
29. Remove Newline Characters
Description: Write a JavaScript program to remove newline (\n) characters from a string.
Input:
"Object Oriented Programming\n"
Expected Output:
"Object Oriented Programming"
30. Split and Join a String
Description: Write a JavaScript program to split a string into words and join them using a hyphen (-).
Input:
"Hello World"
Expected Output:
["Hello", "World"]
"Hello-World"
31. Format a Floating-Point Number
Description: Write a JavaScript program to display a floating-point number with exactly 3 decimal places and convert it into a string.
Input:
2.14652
Expected Output:
"2.147"
32. Convert Number Words into Digits
Description: Write a JavaScript program to convert number words into their corresponding numeric value.
Input:
"five four three two one"
Expected Output:
54321
33. Find the Position of a Word
Description: Write a JavaScript program to find the position of a specified word in a sentence.
Input:
Sentence: "I am solving string problems"
Word: "problems"
Expected Output:
4
34. Count Occurrences of a Word
Description: Write a JavaScript program to count how many times a word appears in a sentence.
Input:
Sentence: "We are learning JavaScript and we are practicing daily"
Word: "are"
Expected Output:
2
35. Find the Least Frequent Character
Description: Write a JavaScript program to identify the character with the lowest frequency in a string.
Input:
"abcdabdggfhf"
Expected Output:
c
36. Find Words Greater Than a Given Length
Description: Write a JavaScript program to display all words whose length is greater than the specified value.
Input:
Length: 3
Sentence: "We are learning JavaScript"
Expected Output:
["learning", "JavaScript"]
37. Get the First Four Characters
Description: Write a JavaScript program to extract the first four characters from a string.
Input:
"JavaScript"
Expected Output:
"Java"
38. Create a String Using the First Two and Last Two Characters
Description: Write a JavaScript program to create a new string using the first two and last two characters.
Input:
"JavaScript"
Expected Output:
"Japt"
39. Print the Mirror Image of a String
Description: Write a JavaScript program to display the mirror image (reverse) of a string.
Input:
"JavaScript"
Expected Output:
"tpircSavaJ"
40. Split a String on Vowels
Description: Write a JavaScript program to split a string wherever a vowel occurs.
Input:
"qwerty"
Expected Output:
["qw", "rty"]
41. Replace Multiple Words
Description: Write a JavaScript program to replace multiple words in a sentence with new words.
Input:
Sentence: "I am learning JavaScript at SQA Tools"
Replace:
JavaScript → JS
SQA Tools → Academy
Expected Output:
"I am learning JS at Academy"
42. Replace Multiple Characters
Description: Write a JavaScript program to replace multiple characters in a string simultaneously.
Input:
String: "JavaScript"
Replace:
a → 1
t → 2
i → 3
Expected Output:
"J1v1Scr3p2"
43. Remove Empty Strings from an Array
Description: Write a JavaScript program to remove empty strings from an array of strings.
Input:
["JavaScript", "", "", "Programming"]
Expected Output:
["JavaScript", "Programming"]
44. Remove Punctuation
Description: Write a JavaScript program to remove all punctuation marks from a string.
Input:
"JavaScript: is great, for web development!"
Expected Output:
"JavaScript is great for web development"
45. Find Duplicate Characters
Description: Write a JavaScript program to display all duplicate characters in a string.
Input:
"hello world"
Expected Output:
"lo"
46. Check Whether One String is a Subset of Another
Description: Write a JavaScript program to determine whether all characters of one string exist in another string.
Input:
Main String: "iamlearningjavascript"
Subset String: "jscript"
Expected Output:
true
47. Sort Characters in a String
Description: Write a JavaScript program to sort all characters of a string in ascending order.
Input:
"xyabkmp"
Expected Output:
"abkmpxy"
48. Generate a Random Binary String
Description: Write a JavaScript program to generate a random binary string of the specified length.
Input:
8
Expected Output:
10100110
49. Check Whether a Substring Exists
Description: Write a JavaScript program to determine whether a given substring exists in a string.
Input:
String: "I live in Pune"
Substring: "live"
Expected Output:
Yes
50. Find Frequency of All Substrings
Description: Write a JavaScript program to calculate the frequency of every possible substring in a string.