Top Playwright TypeScript/JavaScript Interview Questions & Answers
1. What is TypeScript?
TypeScript is a programming language built on JavaScript. It helps you find errors early and makes your code easier to write, understand, and maintain.
//In JavaScript:
let age = 25;
age = "Twenty Five"; // Allowed
JavaScript allows age to change from a number to a string.//But In TypeScript:
let age: number = 25;
age = "Twenty Five"; // Error
Here, age: number means age can contain only numbers.
TypeScript will show an error if you try to assign text to it.In simple words:
TypeScript = JavaScript + Type Safety
It helps find coding mistakes early and makes code easier to maintain.
2. Why do we use TypeScript in Playwright?
TypeScript is useful with Playwright because it makes your automation code safer, easier to write, and easier to maintain.
Main benefits:
Safer functions and test data
You can define exactly what type of data a function should accept.
Catches mistakes early
TypeScript can identify type-related errors before you run your tests.
Better code suggestions
Editors like VS Code can provide better autocomplete for Playwright methods.
Easy to maintain
Larger Page Object Model (POM) frameworks easier to understand and modify.
3. What is the difference between let, const, and var?
All three are used to create variables, but they behave differently.
1. let – value can change
Use let when you know the value may change.
let score = 10;
score = 20;
console.log(score); // 20Easy meaning: let = I may change this value later.
2. const – value cannot be reassigned
Use const when you don’t want to assign a different value later.
const browser = "Chrome";
browser = "Firefox"; //ErrorEasy meaning: const = Keep this value fixed.
3. var – old way of declaring variables.
var name = "Keshav";
name = "Rahul"; // Allowed
var name = "Kapoor"; // Also allowedvar behaves differently from let and const, particularly regarding scope and redeclaration, so modern TypeScript code generally prefers let and const.
| Keyword | Can change value? | Can declare again? | Recommended? |
|---|---|---|---|
let | Yes | No | Yes |
const | No | No | Yes |
var | Yes | Yes | Usually avoid |
let and const are block-scoped, while var is function-scoped. const cannot be reassigned after initialization.
4. What is an Interface?
An interface is like a rule or structure that tells TypeScript what properties an object should have and what type of data those properties can contain.
Interface = Blueprint / Rules for an object
5. What are Modules in TypeScript?
Modules allow us to divide code into separate files and share functionality using export and import.
6. What is any in TypeScript?
any disables type checking for a variable. It allows assigning any type of value.
7. What is a return value?
A return value is the result that a function sends back.
function add(a: number, b: number): number {
return a + b;
}8. What is the difference between == and ===?
== allows type conversion during comparison.
=== checks values without that type coercion.
9. What is forEach()?
forEach() executes a function for every element in an array.
let browsers = ["Chrome", "Firefox", "Edge"];
browsers.forEach(browser => {
console.log(browser);
});An enum is a collection of named constants. It improves readability and avoids hardcoded values.
10. What is length?
length tells us how many elements are in an array or characters are in a string.
let browsers = ["Chrome", "Firefox", "Edge"];
console.log(browsers.length); // 311. What is a Class?
A class is a blueprint for creating objects. It contains properties and methods.
12. What is Inheritance?
Inheritance allows a child class to acquire properties and methods from a parent class. It promotes code reusability.
13. What is Encapsulation?
Encapsulation means keeping data and the methods that work with that data together inside a class, while controlling access where needed.
14. What are Access Modifiers?
Access modifiers control member visibility in a class. The three types are public, private, and protected.
15. What is an Abstract Class?
An abstract class cannot be instantiated directly. It serves as a base class for other classes.
16. What is Method Overloading?
Method overloading allows multiple method signatures with a single implementation. It improves flexibility in method usage.
17. What is extends?
extends is used when one class inherits from another class.
18. What is implements?
Implements is used when a class follows the structure defined by an interface.
interface User {
login(): void;
}
class Admin implements User {
login(): void {
console.log("Login");
}
}19. What is an Object?
An object is an instance of a class.
const user = new User();
20. What is a Constructor?
A constructor is a special method that runs when an object is created. It is commonly used to initialize properties.
21. What is this keyword?
This refers to the current object of the class.
class User {
name = "Keshav";
display() {
console.log(this.name);
}
}22. Why do we use Inheritance?
Inheritance helps reuse common code and reduce duplication.
23. What are Optional Parameters?
Optional parameters are not mandatory during function calls. They are marked using the ? symbol.
24. What is Polymorphism?
Polymorphism means the same method/interface can have different behavior depending on the object.
25. What is Method Overriding?
Method overriding happens when a child class provides its own implementation of a method inherited from its parent.
26. What is Playwright?
Playwright is an open-source automation framework developed by Microsoft for web application testing. It supports Chromium, Firefox, and WebKit browsers.
27. What are the advantages of Playwright over Selenium?
Playwright provides auto-waiting, faster execution, built-in parallel execution, and supports multiple browser engines. It also handles modern web applications more effectively.
28. Which browsers are supported by Playwright?
Playwright supports Chromium, Firefox, and WebKit. It can also automate Google Chrome and Microsoft Edge.
29. What is Browser Context in Playwright?
A Browser Context is an isolated browser session. Multiple contexts can run within a single browser instance without sharing cookies or storage.
30. Difference between Browser and Browser Context?
A Browser is the actual browser instance, while a Browser Context is an independent session within that browser. Contexts help run parallel and isolated tests.
32. What is Page Object Model (POM)?
POM is a design pattern where page elements and actions are stored in separate classes. It improves maintainability and code reusability.
33. What are Locators in Playwright?
Locators are used to identify web elements on a page. They provide auto-waiting and retry mechanisms before performing actions.
34. Which locator is recommended in Playwright?
getByRole() is the most recommended locator because it mimics how users interact with the application. It is stable and accessible.
35. What is Auto-Wait in Playwright?
Playwright automatically waits for elements to become visible, enabled, and actionable before performing operations. This reduces flaky tests.
36. Difference between locator() and page.$()?
locator() supports auto-waiting and retries. page.$() returns the element immediately and may fail if the element is not available.
37. What is test.describe()?
test.describe() is used to group related test cases together. It improves test organization and readability.
38. What is test.beforeEach()?
This hook runs before every test case in a test suite. It is commonly used for login and setup operations.
39. What is test.afterEach()?
This hook runs after every test case execution. It is used for cleanup activities and logging.
40. What is the difference between beforeAll and beforeEach?
beforeAll executes once before all tests. beforeEach executes before every individual test.
41. How do you perform assertions in Playwright?
Playwright uses the expect() library for assertions. It verifies text, visibility, URL, title, and other conditions.
42. How do you handle dropdowns?
Use selectOption() to select dropdown values. Values can be selected by label, value, or index.
43. How do you handle alerts?
Playwright handles alerts using the dialog event. You can accept or dismiss the alert through event handlers.
45. How do you upload files in Playwright?
File upload is handled using setInputFiles(). It directly uploads files without opening the OS file picker.
46. How do you handle multiple tabs?
Use the browser context’s waitForEvent('page') method. It captures and switches control to the new tab.
47. How do you take screenshots in Playwright?
Use the page.screenshot() method. Screenshots can be taken for the full page or a specific element.
48. How do you capture network requests?
Use page.on('request') and page.on('response') events. They allow monitoring of API and network traffic.
49. What is API Testing in Playwright?
Playwright provides APIRequestContext for REST API testing. It allows GET, POST, PUT, and DELETE operations without a browser.
49. How do you run tests in parallel?
Set the workers property in playwright.config.ts. Playwright automatically distributes tests across workers.
50. What is Playwright Trace Viewer?
Trace Viewer is a debugging tool that records test execution details, screenshots, network calls, and actions. It helps analyze test failures.
51. How do you generate an HTML report?
Execute the tests using the HTML reporter configuration. After execution, open the report with npx playwright show-report.
52. How do you handle frames in Playwright?
Playwright uses frameLocator() to work with elements inside an iframe. It provides direct access to frame content.
53. How do you handle authentication in Playwright?
Authentication state can be saved using storageState(). This avoids logging in before every test execution.
54. What is Fixture in Playwright?
Fixtures provide reusable setup and teardown logic for tests. They help reduce code duplication and improve maintainability.
55. What are Hooks in Playwright?
Hooks are methods such as beforeAll, beforeEach, afterEach, and afterAll. They manage preconditions and cleanup activities.
56. Why should companies choose Playwright?
Playwright offers cross-browser support, faster execution, auto-waiting, API testing, tracing, and parallel execution. These features make automation reliable and scalable.
57. How do you run only failed tests from the last run?
npx playwright test –last-failed
58. What is test.skip()?
Skips execution of a particular test.
59. What is test.only()?
Runs only the specified test.
test.only('Login Test', async () => {
});
60. How do you run Playwright tests on multiple browsers?
Playwright supports cross-browser testing, which means the same test can run on Chromium, Firefox, and WebKit without changing the test code.
You configure multiple browsers using the projects section in playwright.config.ts.
projects: [
{ name: ‘chromium’ },
{ name: ‘firefox’ },
{ name: ‘webkit’ }
]
61. What is the readonly keyword?
readonly prevents a property from being modified after initialization.
class User {
readonly id = 101;
}62. Difference between Overloading and Overriding?
Overloading: Same method/function name with different call signatures.
Overriding: Child class replaces an inherited method’s behavior.
63. What is Abstraction?
Abstraction means exposing necessary behavior while hiding implementation details.
64. Can we create an object of an Abstract Class?
No. An abstract class cannot be instantiated directly.
65. Can an Abstract Class have normal methods?
Yes. An abstract class can contain both abstract and implemented methods.
66. Can a class implement multiple interfaces?
Yes.
67. Can an Interface extend another Interface?
Yes
68. What is a Static Method?
A static method is called using the class itself.
69. Can a Child Class have its own methods?
Yes. A child class can inherit methods and also define additional methods.
70. What is super?
super is used in a child class to access the parent class constructor or methods.
71. How would you use Inheritance in an automation framework?
Common methods can be stored in a base class and inherited by page classes.
72. How would you use Encapsulation in automation?
You can keep internal page details private and expose only the operations a test needs.
73. What is an Assertion?
Assertions validate whether an expected result matches the actual result.
They confirm that the application behaves correctly.
Assertions can validate:
Error messages
Page titles
URLs
Success messages
74. How do you run only failed tests from the last run?
npx playwright test --last-failed
75. What are basic assertions in Playwright?
toBeVisible, toHaveText, toHaveURL, toHaveCount, toContainText, and toBeEnabled.
// Check current page URL after login
await expect(page).toHaveURL('/dashboard');
// Check page title
await expect(page).toHaveTitle('My App - Dashboard');
// Check element is visible on screen
await expect(page.locator('.success-msg')).toBeVisible();
// Check element has specific text
await expect(page.locator('h1')).toHaveText('Welcome, Rahul');
// Check element does NOT exist or is NOT visible
await expect(page.locator('.error-msg')).not.toBeVisible();76. Why should you avoid waitForTimeout?
page.waitForTimeout(2000) pauses for a fixed duration. It is the test-automation equivalent of Thread.sleep, and it causes flaky tests for 2 reasons:
77. How do you configure screenshots, videos, and traces?
export default defineConfig({
use: {
screenshot: 'only-on-failure', // 'on' | 'off' | 'only-on-failure'
video: 'retain-on-failure', // 'on' | 'off' | 'retain-on-failure' | 'on-first-retry'
trace: 'on-first-retry', // 'on' | 'off' | 'retain-on-failure' | 'on-first-retry'
},
});78.How do you run only one specific test in Playwright?
// Use test.only() to run just this one test
test.only('Login test', async ({ page }) => {
// only this test will run in this file
});
// Remember to remove .only before committing to Git!79. How does parallel execution work?
Playwright runs tests in parallel by default. Each worker is a separate Node.js process running its own browser. The runner distributes test files across workers.
// playwright.config.ts
export default defineConfig({
fullyParallel: true, // run tests within a file in parallel too
workers: process.env.CI ? 4 : undefined, // 4 in CI, half your CPU cores locally
});80. What are Locators in Playwright?
// By role — most recommended, works with accessibility
page.getByRole('button', { name: 'Login' })
page.getByRole('textbox', { name: 'Email' })
// By visible text on screen
page.getByText('Welcome to STAD Solution')
// By placeholder text inside an input
page.getByPlaceholder('Enter your email')
// By label text (for form fields)
page.getByLabel('Password')
// By test ID — most stable for automation
page.getByTestId('submit-button')
// By CSS selector
page.locator('#email-input')
page.locator('.btn-primary')81. How do you check if an element is visible or exists on the page?
Playwright provides two methods — isVisible() returns true or false, while toBeVisible() is an assertion that fails the test if the element is not visible.
// Check visibility — returns true or false
const isVisible = await page.locator('.success-msg').isVisible();
console.log(isVisible); // true or false
// Assert element IS visible — test fails if not
await expect(page.locator('.success-msg')).toBeVisible();
// Assert element is NOT visible
await expect(page.locator('.error-msg')).not.toBeVisible();
// Check if element exists in DOM (even if hidden)
const exists = await page.locator('#modal').count() > 0;
console.log(exists); // true if present in HTML82. What is the difference between fill() and type() in Playwright?
| Method | How it works | Speed | Use when |
|---|---|---|---|
| fill() | Clears the field and sets value directly | Fast | Most form inputs — standard text, email, password |
| type() | Simulates actual key press for each character | Slow | Search inputs with live autocomplete suggestions |
// fill() — use for most inputs
await page.fill('#email', 'kapoor@gmail.com');
// type() — use for autocomplete search inputs
// Each keypress triggers a suggestion list update
await page.locator('#city-search').type('Noida');
await page.locator('.suggestion-item').first().click();83. How do you scroll to an element or scroll the page?
Playwright automatically scrolls to elements before clicking them. But sometimes you need to scroll manually — like to load lazy-loaded content or to scroll inside a specific container.
// Scroll a specific element into view
await page.locator('#footer-section').scrollIntoViewIfNeeded();
// Scroll to bottom of page (for lazy loading)
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
// Scroll to top of page
await page.evaluate(() => window.scrollTo(0, 0));
84. How do you use tags to run only specific tests?
Tags help you organize and selectively run tests. Add tags using @tag in the test name, then filter by tag from the terminal.
// Add @tags to test names
test('Login test @smoke', async ({ page }) => { });
test('Checkout test @smoke @regression', async ({ page }) => { });
test('Profile update @regression', async ({ page }) => { });
test('Payment @regression @payment', async ({ page }) => { });# Run only smoke tests (quick sanity check)
npx playwright test --grep @smoke
# Run full regression suite
npx playwright test --grep @regression
# Run only payment-related tests
npx playwright test --grep @payment
# Skip smoke tests, run everything else
npx playwright test --grep-invert @smoke85.What is the Playwright HTML Report and Trace Viewer?
Playwright has two powerful built-in tools for understanding test results:
HTML Report — A visual report showing all test results with pass/fail status, screenshots, error messages, and test duration. You can share this with your team or manager after a test run.
Trace Viewer — A step-by-step recording of everything that happened during a test — every click, every network call, every DOM snapshot. When a test fails, you open the trace to see exactly what went wrong.
//playwright.config.js — Enable trace and report
reporter: ['html'], // generates HTML report
use: {
trace: 'retain-on-failure', // save trace only when test fails
screenshot: 'only-on-failure', // save screenshot on failure
video: 'retain-on-failure', // save video on failure
}//Terminal
# Open HTML report in browser
npx playwright show-report
# Open trace file to debug a failure
npx playwright show-trace trace.zip86. What are test.skip(), test.only(), and test.fixme() used for?
Playwright provides two methods — isVisible() returns true or false, while toBeVisible() is an assertion that
| Method | What it does | When to use |
|---|---|---|
| test.skip() | Test is skipped — not run at all | Feature not yet built, or test environment issue |
| test.only() | Only this test runs — all others are skipped | Temporarily run one test during development |
| test.fixme() | Test runs but is expected to fail — shown separately | Known bug tracked in JIRA — test documents the bug |
// Skip this test completely
test.skip('Payment test — gateway is down in staging', async ({ page }) => {
// will not run
});
// Run ONLY this test (remove before committing!)
test.only('Login test', async ({ page }) => {
// only this runs
});
// Known bug — test runs but failure is expected
test.fixme('Cart count is wrong — BUG-1234', async ({ page }) => {
// documents the known bug
});
// Conditional skip — skip on Firefox only
test('Chrome-only feature test', async ({ page, browserName }) => {
test.skip(browserName !== 'chromium', 'This feature is Chrome-only');
// rest of test
});87.How would you handle a CAPTCHA in your automation tests?
CAPTCHA is designed to prevent automated access, so I would not try to automate or solve it directly. In the test or staging environment, I would work with the development/security team to disable CAPTCHA.
88. Explain Playwright’s auto-waiting mechanism.
Before performing an action such as click, Playwright checks whether the target is ready.
For example, it checks that the element is visible, stable, enabled and able to receive the event.
89. What are timeouts in Playwright?
Timeout ensures that before marking test execution as a failure the amount of time the Playwright needs to wait.
90. How to navigate forward and backward in Playwright?
The playwright provides specific commands to navigate backward and forward.
page.goForward() command can be used to navigate forward from the browser history
page.goBack() command can be used to navigate backward from the browser history
91. How do you perform single-click, double-click, and right-click in Playwright?
In Playwright, you can perform these mouse actions using locator methods.
//1. Single Click
await page.getByRole('button').click();
//2. Double Click
await page.getByText('Item').dblclick();
//3. Right Click
await page.getByText('Item').click({ button: 'right' });
92. What does void mean?
void means a function does not return a useful value.
function message(): void {
console.log(“Hello”);
}
93. How do you hover over an element?
await page.getByText(‘Products’).hover();
94. How do you refresh or reload a page?
await page.reload();
95. How do you get the page title?
const title = await page.title();
console.log(title);
96. What does await mean in a Playwright test?
await waits for an asynchronous operation to complete before the next statement continues.
await page.goto(‘https://logicnextgen.com/‘);
await page.getByRole(‘button’).click();
97. How do you check whether a button is enabled?
await expect(page.getByRole(‘button’)).toBeEnabled();
98. What is test() in Playwright?
await page.reload();
test() defines a test case.
test(‘Login Test’, async ({ page }) => {
// test steps
});
99. What does expect() do?
expect() is used to verify expected behavior.
await expect(page.getByText(‘Welcome’)).toBeVisible();
100. How do you press the Enter key from keyboard?
await page.keyboard.press(‘Enter’);