Skip to content

Playwright Testing Interview Questions & Answers (2026)

Practice interview questions and answers organized by company, salary package, topic and difficulty. Mark questions as solved to keep track of your preparation.

Questions solvedStart practicing
3 QUESTIONS FREESign up or log in to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
02

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
03

interface vs type in TypeScript?

Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
04

How do you reuse login state across tests?

Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
05

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
06

How do you share cookies between API login and UI?

Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
07

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
08

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
09

How do you integrate Playwright with Allure or other reports?

Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
10

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
11

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
12

What are generics in TypeScript?

Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
13

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
14

How do you reuse login state across tests?

Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
15

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
16

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
17

How do you test pagination or chained API calls?

Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
18

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
19

Explain the event loop.

Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
20

What is the difference between map, filter and reduce?

Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
21

Which locators does Playwright recommend?

Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
22

How do you run tests in parallel and control workers?

Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
23

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
24

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
25

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
26

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
27

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
28

How do you test geolocation, permissions and time zones?

Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
29

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
30

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
31

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
32

What reporters does Playwright provide?

Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
33

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
34

What is the difference between null and undefined?

Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
35

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
36

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
37

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
38

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
39

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
40

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
41

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
42

How do you structure environment-specific configs in Playwright?

Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
43

What does the optional chaining operator do?

Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
44

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
45

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
46

How do you handle token refresh in long API test runs?

Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
47

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
48

How do you run tests in Docker?

Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
49

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
50

How do you share cookies between API login and UI?

Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
51

What are generics in TypeScript?

Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
52

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
53

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
54

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
55

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
56

Promise.all vs Promise.allSettled vs Promise.race?

Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
57

What is the difference between map, filter and reduce?

Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
58

How do you run Playwright in GitHub Actions?

Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
59

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
60

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
61

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
62

How do you debug a Playwright test?

Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
63

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
64

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
65

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
66

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
67

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
68

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
69

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
70

How do you perform drag and drop and hover?

Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
71

What are fixtures in Playwright?

Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
72

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
73

How do you mock third-party APIs in UI tests?

Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
74

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
75

How do you reuse login state across tests?

Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
76

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
77

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
78

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
79

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
80

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
81

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
82

What is the difference between null and undefined?

Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
83

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
84

What are web-first assertions?

Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
85

How do you run Playwright in GitHub Actions?

Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
86

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
87

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
88

How do you handle date pickers and custom dropdowns?

Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
89

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
90

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
91

What are generics in TypeScript?

Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
92

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
93

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
94

Promise.all vs Promise.allSettled vs Promise.race?

Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
95

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
96

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
97

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
98

What is APIRequestContext?

Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
99

How do you integrate Playwright with Allure or other reports?

Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
100

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
101

How do you debug a Playwright test?

Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
102

How do you combine API and UI tests?

Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
103

How do you send authentication headers?

Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
104

How do you test pagination or chained API calls?

Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
105

How do you run tests in parallel and control workers?

Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
106

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
107

What is the difference between map, filter and reduce?

Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
108

How do you handle authentication to avoid logging in every test?

Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
109

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
110

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
111

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
112

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
113

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
114

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
115

How do you manage test data and environments?

Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
116

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
117

How do you handle token refresh in long API test runs?

Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
118

How do you handle file uploads and downloads?

Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
119

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
120

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
121

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
122

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
123

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
124

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
125

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
126

What is the difference between synchronous and asynchronous code?

Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
127

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
128

How do you mock third-party APIs in UI tests?

Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
129

How do you manage test data and environments?

Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
130

How do you wait for a network response in Playwright?

Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
131

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
132

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
133

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
134

How do you share cookies between API login and UI?

Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
135

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
136

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
137

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
138

How do you handle shadow DOM?

Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
139

How do you handle date pickers and custom dropdowns?

Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
140

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
141

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
142

What are interfaces and types in TypeScript?

Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
143

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
144

What is hoisting?

Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
145

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
146

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
147

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
148

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
149

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
150

How do you perform drag and drop and hover?

Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
151

How do you handle authentication to avoid logging in every test?

Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
152

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
153

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
154

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
155

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
156

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
157

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
158

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
159

How do you do visual regression testing?

Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
160

What is APIRequestContext?

Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
161

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
162

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
163

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
164

How do you structure environment-specific configs in Playwright?

Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
165

What reporters does Playwright provide?

Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
166

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
167

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
168

What are closures?

Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
169

How do you handle file uploads and downloads?

Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
170

What is the difference between synchronous and asynchronous code?

Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
171

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
172

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
173

Explain the event loop.

Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
174

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
175

What is the difference between map, filter and reduce?

Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
176

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
177

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
178

What happens if you forget an await?

Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
179

Promise.all vs Promise.allSettled vs Promise.race?

Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
180

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
181

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
182

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
183

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
184

What is APIRequestContext?

Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
185

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
186

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
187

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
188

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
189

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
190

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
191

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
192

What are soft assertions?

Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
193

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
194

How do you handle file uploads and downloads?

Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
195

What are generics in TypeScript?

Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
196

How do you mock third-party APIs in UI tests?

Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
197

How do you send a POST request with a JSON body?

Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
198

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
199

How do you test pagination or chained API calls?

Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
200

How do you reuse login state across tests?

Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
201

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
202

How do you structure environment-specific configs in Playwright?

Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
203

How do you run tests in Docker?

Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
204

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
205

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
206

What are global setup and teardown?

Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
207

What is the difference between click and dispatchEvent?

Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
208

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
209

What are fixtures in Playwright?

Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
210

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
211

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
212

Explain the event loop.

Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
213

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
214

How do you mock network requests?

Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
215

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
216

What are interfaces and types in TypeScript?

Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
217

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
218

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
219

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
220

How do you handle rate limits or slow APIs in tests?

Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
221

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
222

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
223

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
224

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
225

How do you structure environment-specific configs in Playwright?

Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
226

How do you run tests in Docker?

Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
227

How do you run tests on mobile viewports?

Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
228

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
229

How do you send a POST request with a JSON body?

Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
230

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
231

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
232

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
233

How do you set test timeouts?

Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
234

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
235

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
236

What is APIRequestContext?

Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
237

What reporters does Playwright provide?

Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
238

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
239

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
240

How do you wait for a network response in Playwright?

Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
241

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
242

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
243

What are generics in TypeScript?

Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
244

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
245

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
246

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
247

How do you combine API and UI tests?

Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
248

What is the difference between map, filter and reduce?

Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
249

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
250

Promise.all vs Promise.allSettled vs Promise.race?

Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
251

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
252

What does the optional chaining operator do?

Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
253

What are fixtures in Playwright?

Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
254

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
255

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
256

How do you mock third-party APIs in UI tests?

Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
257

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
258

How do you do visual regression testing?

Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
259

How do you set test timeouts?

Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
260

What are higher-order functions?

Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
261

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
262

How do you reuse login state across tests?

Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
263

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
264

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
265

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
266

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
267

What are fixtures in Playwright?

Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
268

How do you handle rate limits or slow APIs in tests?

Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
269

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
270

What does the optional chaining operator do?

Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
271

How do you handle date pickers and custom dropdowns?

Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
272

What are soft assertions?

Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
273

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
274

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
275

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
276

How do you run tests in Docker?

Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
277

What is the difference between null and undefined?

Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
278

interface vs type in TypeScript?

Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
279

How do you wait for a network response in Playwright?

Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
280

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
281

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
282

What happens if you forget an await?

Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
283

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
284

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
285

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
286

How do you mock third-party APIs in UI tests?

Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
287

How do you run tests on mobile viewports?

Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
288

How do you test geolocation, permissions and time zones?

Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
289

How do you structure environment-specific configs in Playwright?

Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
290

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
291

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
292

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
293

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
294

Which locators does Playwright recommend?

Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
295

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
296

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
297

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
298

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
299

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
300

What is the difference between synchronous and asynchronous code?

Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
301

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
302

How do you integrate Playwright with Allure or other reports?

Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
303

Explain the event loop.

Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
304

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
305

How do you debug a Playwright test?

Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
306

What is APIRequestContext?

Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
307

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
308

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
309

How do you test a file download?

Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
310

How do you handle shadow DOM?

Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
311

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
312

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
313

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
314

How do you test geolocation, permissions and time zones?

Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
315

Write an API test with the request fixture.

Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
316

How do you handle token refresh in long API test runs?

Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
317

Promise.all vs Promise.allSettled vs Promise.race?

Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
318

How do you handle authentication to avoid logging in every test?

Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
319

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
320

What are web-first assertions?

Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
321

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
322

How do you handle file uploads and downloads?

Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
323

How do you set test timeouts?

Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
324

Which locators does Playwright recommend?

Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
325

How do you handle date pickers and custom dropdowns?

Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
326

What does the optional chaining operator do?

Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
327

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
328

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
329

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
330

How do you send authentication headers?

Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
331

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
332

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
333

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
334

How do you handle token refresh in long API test runs?

Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
335

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
336

How do you perform drag and drop and hover?

Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
337

Explain the event loop.

Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
338

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
339

How do you run Playwright in GitHub Actions?

Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
340

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
341

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
342

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
343

How do you send authentication headers?

Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
344

How do you handle file uploads and downloads?

Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
345

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
346

What are interfaces and types in TypeScript?

Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
347

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
348

How do you handle rate limits or slow APIs in tests?

Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
349

How do you reuse login state across tests?

Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
350

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
351

What are generics in TypeScript?

Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
352

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
353

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
354

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
355

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
356

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
357

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
358

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
359

What reporters does Playwright provide?

Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
360

What are closures?

Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
361

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
362

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
363

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
364

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
365

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
366

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
367

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
368

How do you combine API and UI tests?

Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
369

Promise.all vs Promise.allSettled vs Promise.race?

Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
370

What are global setup and teardown?

Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
371

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
372

How do you do visual regression testing?

Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
373

Write an API test with the request fixture.

Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
374

What is APIRequestContext?

Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
375

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
376

What is the difference between null and undefined?

Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
377

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
378

interface vs type in TypeScript?

Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
379

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
380

How do you wait for a network response in Playwright?

Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
381

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
382

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
383

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
384

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
385

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
386

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
387

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
388

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
389

How do you handle date pickers and custom dropdowns?

Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
390

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
391

How do you handle shadow DOM?

Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
392

How do you run tests on mobile viewports?

Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
393

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
394

How do you set test timeouts?

Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
395

What are web-first assertions?

Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
396

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
397

What reporters does Playwright provide?

Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
398

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
399

What are web-first assertions?

Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
400

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
401

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
402

Promise.all vs Promise.allSettled vs Promise.race?

Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
403

How do you run Playwright in GitHub Actions?

Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
404

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
405

What are global setup and teardown?

Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
406

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
407

How do you test pagination or chained API calls?

Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
408

What happens if you forget an await?

Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
409

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
410

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
411

What is the difference between click and dispatchEvent?

Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
412

How do you run tests in parallel and control workers?

Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
413

How do you share cookies between API login and UI?

Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
414

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
415

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
416

How do you handle rate limits or slow APIs in tests?

Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
417

What is APIRequestContext?

Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
418

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
419

How do you handle date pickers and custom dropdowns?

Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
420

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
421

What does the optional chaining operator do?

Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
422

What are higher-order functions?

Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
423

What are generics in TypeScript?

Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
424

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
425

How do you run tests in Docker?

Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
426

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
427

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
428

Write an API test with the request fixture.

Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
429

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
430

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
431

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
432

How do you handle file uploads and downloads?

Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
433

How do you debug a Playwright test?

Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
434

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
435

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
436

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
437

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
438

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
439

How do you integrate Playwright with Allure or other reports?

Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
440

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
441

How do you mock third-party APIs in UI tests?

Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
442

How do you share cookies between API login and UI?

Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
443

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
444

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
445

Explain the event loop.

Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
446

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
447

Which locators does Playwright recommend?

Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
448

interface vs type in TypeScript?

Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
449

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
450

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
451

What is auto-waiting in Playwright?

TCSEasy
Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
452

How do you create test data through the API before a UI test?

TCSHard
Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
453

interface vs type in TypeScript?

TCSMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
454

What is destructuring and the spread operator?

TCSMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
455

What is the difference between TypeScript and JavaScript?

TCSEasy
Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
456

How do you debug a Playwright test?

TCSMedium
Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
457

Why choose Playwright over Selenium?

TCSMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
458

How do you handle multiple tabs or pop-ups?

InfosysMedium
Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
459

What are fixtures in Playwright?

InfosysMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
460

What is the difference between beforeEach and fixtures?

InfosysMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
461

Explain the event loop.

InfosysMedium
Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
462

What is the difference between null and undefined?

InfosysMedium
Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
463

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
464

How do you test pagination or chained API calls?

InfosysMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
465

What are global setup and teardown?

InfosysMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
466

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
467

Write an API test with the request fixture.

InfosysMedium
Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
468

What are template literals?

InfosysMedium
Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
469

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
470

How do you take screenshots and videos?

InfosysMedium
Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
471

How do you test file downloads and verify their content?

InfosysMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
472

How do you set test timeouts?

InfosysMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
473

How do you handle token refresh in long API test runs?

InfosysMedium
Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
474

How do you handle file uploads and downloads?

InfosysMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
475

Why choose Playwright over Selenium?

InfosysMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
476

How do you mock third-party APIs in UI tests?

InfosysMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
477

How do you debug a Playwright test?

InfosysMedium
Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
478

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
479

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
480

How do you mock network requests?

InfosysMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
481

What is hoisting?

WiproMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
482

How do you integrate Playwright with Allure or other reports?

WiproMedium
Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
483

How do you run tests in parallel and control workers?

WiproMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
484

What are template literals?

WiproMedium
Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
485

What is APIRequestContext?

WiproMedium
Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
486

How do you create test data through the API before a UI test?

WiproHard
Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
487

How do you mock an API response?

WiproMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
488

How do you handle rate limits or slow APIs in tests?

WiproMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
489

How do you test geolocation, permissions and time zones?

WiproMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
490

How do you handle file uploads and downloads?

WiproMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
491

How do you combine API and UI tests?

WiproMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
492

How does Playwright compare with Selenium and Cypress?

WiproMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
493

What is the difference between a type and an enum in TypeScript?

WiproMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
494

What are higher-order functions?

WiproMedium
Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
495

How do you test file downloads and verify their content?

WiproMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
496

How do you handle iframes in Playwright?

WiproMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
497

How do you reuse login state across tests?

WiproMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
498

How do you test a file download?

WiproMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
499

Tests are flaky in CI. How do you debug them?

WiproHard
Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
500

How do you do visual regression testing?

WiproMedium
Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
501

How do you work with iframes?

WiproEasy
Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
502

How does visual testing work in Playwright?

WiproMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
503

What is the difference between TypeScript and JavaScript?

WiproEasy
Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
504

What are the main data types in JavaScript?

WiproEasy
Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
505

How do you run tests on three browsers in parallel?

WiproEasy
Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
506

Which locators does Playwright recommend?

WiproMedium
Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
507

What is Playwright and which browsers does it support?

WiproEasy
Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
508

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
509

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
510

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
511

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
512

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
513

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
514

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
515

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
516

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
517

How do you run tests in parallel and control workers?

Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
518

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
519

How do you reuse login state across tests?

Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
520

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
521

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
522

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
523

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
524

How do you run tests on mobile viewports?

Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
525

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
526

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
527

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
528

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
529

How do you integrate Playwright with Allure or other reports?

Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
530

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
531

Promise.all vs Promise.allSettled vs Promise.race?

Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
532

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
533

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
534

How do you mock network requests?

Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
535

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
536

What are soft assertions?

Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
537

What is hoisting?

Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
538

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
539

What are web-first assertions?

Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
540

How do you handle file uploads and downloads?

Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
541

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
542

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
543

How do you do visual regression testing?

Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
544

How do you handle authentication to avoid logging in every test?

Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
545

Write an API test with the request fixture.

Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
546

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
547

What are fixtures in Playwright?

Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
548

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
549

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
550

How do you reuse login state across tests?

Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
551

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
552

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
553

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
554

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
555

How do you wait for a network response in Playwright?

Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
556

Which locators does Playwright recommend?

Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
557

How do you handle date pickers and custom dropdowns?

Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
558

What are higher-order functions?

Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
559

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
560

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
561

How do you organise tests with page object model in Playwright?

GoogleMedium
Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
562

Promise.all vs Promise.allSettled vs Promise.race?

GoogleMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
563

How do you test accessibility with Playwright?

GoogleMedium
Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
564

What are fixtures in Playwright?

GoogleMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
565

How do you mock network requests?

GoogleMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
566

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
567

How do you tag and filter tests?

GoogleMedium
Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
568

How do you manage test data and environments?

GoogleMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
569

What are higher-order functions?

LinkedInMedium
Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
570

How do you combine API and UI tests?

LinkedInMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
571

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
572

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
573

How do you integrate Playwright with Allure or other reports?

Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
574

What are global setup and teardown?

Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
575

How do you perform drag and drop and hover?

Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
576

How do you reuse login state across tests?

Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
577

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
578

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
579

How do you share cookies between API login and UI?

Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
580

How do retries work?

UberMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
581

How do you run tests in Docker?

Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
582

How do you test pagination or chained API calls?

Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
583

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
584

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
585

How do you manage test data and environments?

Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
586

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
587

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
588

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
589

What are soft assertions?

Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
590

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
591

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
592

What does the optional chaining operator do?

StripeMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
593

How do you test pagination or chained API calls?

StripeMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
594

How does visual testing work in Playwright?

StripeMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
595

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
596

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
597

How do you send authentication headers?

PayPalMedium
Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
598

How do you shard tests across machines?

PayPalMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
599

How do you handle shadow DOM?

PayPalMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
600

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
601

How do you mock network requests?

PayPalMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
602

Write an API test with the request fixture.

PayPalMedium
Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
603

How do you test pagination or chained API calls?

PayPalMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
604

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
605

How do you handle GraphQL APIs in Playwright?

PayPalMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
606

How do you wait for a network response in Playwright?

PayPalMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
607

How do you set test timeouts?

PayPalMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
608

How do you run tests on mobile viewports?

PayPalMedium
Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
609

What are soft assertions?

PayPalMedium
Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
610

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
611

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
612

How do you handle authentication to avoid logging in every test?

PayPalMedium
Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
613

How do you take screenshots and videos?

PayPalMedium
Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
614

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
615

What is the difference between map, filter and reduce?

PayPalMedium
Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
616

How do you test a file download?

PayPalMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
617

How do you run tests in Docker?

PayPalMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
618

interface vs type in TypeScript?

PayPalMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
619

How does Playwright compare with Selenium and Cypress?

PayPalMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
620

How do you handle dialogs such as alerts?

PayPalMedium
Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
621

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
622

How do retries work?

PayPalMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
623

How do you combine API and UI tests?

PayPalMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
624

Which locators does Playwright recommend?

PayPalMedium
Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
625

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
626

What is APIRequestContext?

PayPalMedium
Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
627

What is the difference between a type and an enum in TypeScript?

PayPalMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
628

What reporters does Playwright provide?

PayPalMedium
Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
629

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
630

What is codegen?

PayPalMedium
Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
631

How do you debug a Playwright test?

PayPalMedium
Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
632

What is the difference between null and undefined?

PayPalMedium
Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
633

What is the difference between map, filter and reduce?

Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
634

How do you do visual regression testing?

Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
635

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
636

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
637

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
638

What are closures?

Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
639

How do you run tests in parallel and control workers?

Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
640

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
641

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
642

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
643

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
644

How do you combine API and UI tests?

Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
645

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
646

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
647

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
648

What is APIRequestContext?

Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
649

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
650

How do you run Playwright in GitHub Actions?

Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
651

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
652

What reporters does Playwright provide?

Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
653

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
654

Explain the event loop.

Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
655

How do you mock third-party APIs in UI tests?

Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
656

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
657

How do you test geolocation, permissions and time zones?

Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
658

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
659

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
660

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
661

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
662

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
663

What is hoisting?

Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
664

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
665

How do you shard tests across machines?

AdobeMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
666

How do you validate an API response in Playwright?

AdobeMedium
Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
667

What is the difference between page, context and browser?

AdobeMedium
Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
668

interface vs type in TypeScript?

AdobeMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
669

How do you use test.step and test annotations?

AdobeMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
670

How do you make an API request in Playwright?

AdobeEasy
Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
671

How do you handle a new tab?

AdobeEasy
Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
672

What is the difference between beforeEach and fixtures?

AdobeMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
673

How do you organise tests with page object model in Playwright?

AdobeMedium
Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
674

How do you run tests on three browsers in parallel?

AdobeEasy
Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
675

How do you handle file uploads and downloads?

FlipkartMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
676

How do you test accessibility with Playwright?

FlipkartMedium
Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
677

How do you take screenshots and videos?

FlipkartMedium
Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
678

What are generics in TypeScript?

FlipkartMedium
Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
679

How do you test a file download?

FlipkartMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
680

How do you handle authentication to avoid logging in every test?

FlipkartMedium
Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
681

How do you test file downloads and verify their content?

FlipkartMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
682

How does Playwright compare with Selenium and Cypress?

FlipkartMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
683

How do you test pagination or chained API calls?

FlipkartMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
684

How do you manage test data and environments?

FlipkartMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
685

How do you set test timeouts?

FlipkartMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
686

What is the difference between waitForSelector and expect with locator?

FlipkartMedium
Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
687

What is the difference between a type and an enum in TypeScript?

FlipkartMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
688

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
689

What are soft assertions?

FlipkartMedium
Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
690

How does Playwright's trace viewer help?

FlipkartMedium
Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
691

What are closures?

FlipkartMedium
Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
692

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
693

How do you use test.step and test annotations?

FlipkartMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
694

What are projects in playwright.config?

FlipkartMedium
Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
695

What are global setup and teardown?

FlipkartMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
696

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
697

How do you mock an API response?

ZomatoMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
698

What is the difference between a type and an enum in TypeScript?

ZomatoMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
699

How do you combine API and UI tests?

ZomatoMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
700

Write an API test with the request fixture.

ZomatoMedium
Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
701

How do you validate an API response in Playwright?

ZomatoMedium
Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
702

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
703

How do you perform drag and drop and hover?

ZomatoMedium
Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
704

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
705

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
706

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
707

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
708

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
709

What are fixtures and how do you create a custom one?

ZomatoMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
710

How does Playwright's trace viewer help?

ZomatoMedium
Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
711

How do you mock third-party APIs in UI tests?

ZomatoMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
712

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
713

How do you handle date pickers and custom dropdowns?

ZomatoMedium
Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
714

Explain the event loop.

ZomatoMedium
Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
715

How do retries work?

ZomatoMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
716

How do you test file downloads and verify their content?

ZomatoMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
717

How do you measure API response time?

ZomatoMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
718

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
719

What is hoisting?

ZomatoMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
720

What is the difference between synchronous and asynchronous code?

ZomatoMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
721

How do you run tests in Docker?

ZomatoMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
722

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
723

What is destructuring and the spread operator?

ZomatoMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
724

What are interfaces and types in TypeScript?

ZomatoMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
725

How do you send authentication headers?

ZomatoMedium
Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
726

What are global setup and teardown?

ZomatoMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
727

What is the difference between null and undefined?

ZomatoMedium
Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
728

What is the difference between click and dispatchEvent?

ZomatoMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
729

What does the optional chaining operator do?

ZomatoMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
730

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
731

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
732

How do you test file upload via API?

ZomatoMedium
Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
733

What is the difference between synchronous and asynchronous code?

SwiggyMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
734

How does visual testing work in Playwright?

SwiggyMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
735

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
736

How do you test accessibility with Playwright?

SwiggyMedium
Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
737

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
738

How do you combine API and UI tests?

SwiggyMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
739

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
740

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
741

What are generics in TypeScript?

SwiggyMedium
Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
742

How do you test pagination or chained API calls?

SwiggyMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
743

How do you perform drag and drop and hover?

SwiggyMedium
Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
744

What is the difference between click and dispatchEvent?

SwiggyMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
745

How do you debug a Playwright test?

SwiggyMedium
Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
746

What is codegen?

SwiggyMedium
Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
747

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
748

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
749

How do you reuse login state across tests?

SwiggyMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
750

How do you send a POST request with a JSON body?

SwiggyMedium
Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
751

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
752

How do you set test timeouts?

SwiggyMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
753

How do you mock network requests?

SwiggyMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
754

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
755

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
756

What are interfaces and types in TypeScript?

SwiggyMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
757

Explain the event loop.

SwiggyMedium
Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
758

What are fixtures and how do you create a custom one?

SwiggyMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
759

What are soft assertions?

SwiggyMedium
Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
760

How do you shard tests across machines?

SwiggyMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
761

How do you handle authentication to avoid logging in every test?

SwiggyMedium
Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
762

What are higher-order functions?

SwiggyMedium
Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
763

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
764

How do you measure API response time?

SwiggyMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
765

How do you handle multiple tabs or pop-ups?

SwiggyMedium
Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
766

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
767

How do you handle file uploads and downloads?

SwiggyMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
768

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
769

What are closures?

SwiggyMedium
Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
770

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
771

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
772

How do you validate JSON schema?

SwiggyMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
773

How does Playwright's trace viewer help?

SwiggyMedium
Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
774

What is the difference between a type and an enum in TypeScript?

SwiggyMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
775

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
776

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
777

How do you test file downloads and verify their content?

SwiggyMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
778

How do you test file upload via API?

SwiggyMedium
Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
779

How does Playwright compare with Selenium and Cypress?

SwiggyMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
780

How would you structure a large Playwright framework for a team?

ZeptoHard
Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
781

How do you test file downloads and verify their content?

PaytmMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
782

How do you validate JSON schema?

PaytmMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
783

How would you design API test coverage for a new endpoint?

PaytmHard
Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
784

How do you tag and filter tests?

PaytmMedium
Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
785

How do you test pagination or chained API calls?

PaytmMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
786

What is npm and package.json?

PaytmEasy
Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
787

Explain the event loop.

PaytmMedium
Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
788

What are higher-order functions?

PaytmMedium
Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
789

What is APIRequestContext?

PaytmMedium
Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
790

How do you mock network requests?

PaytmMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
791

How do you work with iframes?

PaytmEasy
Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
792

What is the difference between click and dispatchEvent?

PaytmMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
793

How do you test a file download?

PaytmMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
794

How do you handle shadow DOM?

PaytmMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
795

How would you structure a large Playwright framework for a team?

PaytmHard
Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
796

What does the optional chaining operator do?

PaytmMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
797

How do you combine API and UI tests?

PaytmMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
798

What happens if you forget an await?

PaytmMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
799

What is hoisting?

PaytmMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
800

How do you run a single test or file in Playwright?

PaytmEasy
Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
801

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
802

What are interfaces and types in TypeScript?

Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
803

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
804

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
805

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
806

How do you handle shadow DOM?

Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
807

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
808

What is hoisting?

Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
809

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
810

Explain the event loop.

Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
811

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
812

How do you reuse login state across tests?

Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
813

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
814

How do you mock network requests?

Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
815

How do you share cookies between API login and UI?

Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
816

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
817

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
818

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
819

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
820

What are web-first assertions?

Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
821

How do you debug a Playwright test?

Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
822

What happens if you forget an await?

Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
823

How do you run tests on mobile viewports?

Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
824

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
825

What are soft assertions?

Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
826

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
827

How do you run Playwright in GitHub Actions?

Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
828

How do you set test timeouts?

Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
829

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
830

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
831

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
832

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
833

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
834

How do you mock third-party APIs in UI tests?

Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
835

How do you tag and filter tests?

IntuitMedium
Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
836

How do you take screenshots and videos?

IntuitMedium
Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
837

What is destructuring and the spread operator?

IntuitMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
838

What is APIRequestContext?

IntuitMedium
Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
839

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
840

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
841

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
842

How do you test file upload via API?

IntuitMedium
Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
843

What is the difference between synchronous and asynchronous code?

IntuitMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
844

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
845

How do you handle shadow DOM?

IntuitMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
846

How do you reuse login state across tests?

WalmartMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
847

What is the difference between waitForSelector and expect with locator?

WalmartMedium
Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
848

What does the optional chaining operator do?

WalmartMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
849

How do you manage test data and environments?

WalmartMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
850

How do you test API error scenarios?

WalmartMedium
Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
851

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
852

How do you share cookies between API login and UI?

WalmartMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
853

What are generics in TypeScript?

WalmartMedium
Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
854

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
855

How do you share cookies between API login and UI?

VisaMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
856

How do you handle shadow DOM?

VisaMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
857

How do you send authentication headers?

HSBCMedium
Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
858

How do you handle multiple tabs or pop-ups?

HSBCMedium
Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
859

How do you wait for a network response in Playwright?

HSBCMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
860

How do you handle authentication to avoid logging in every test?

HSBCMedium
Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
861

How do you run tests on three browsers in parallel?

HSBCEasy
Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
862

What is the difference between waitForSelector and expect with locator?

HSBCMedium
Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
863

How do you mock network requests?

HSBCMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
864

What are global setup and teardown?

HSBCMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
865

How do you handle iframes in Playwright?

HSBCMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
866

How do you debug a Playwright test?

HSBCMedium
Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
867

How do you handle errors in async code?

HSBCEasy
Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
868

What are the main data types in JavaScript?

HSBCEasy
Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
869

What is hoisting?

HSBCMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
870

How does Playwright compare with Selenium and Cypress?

HSBCMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
871

How do you validate JSON schema?

HSBCMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
872

How do you test file downloads and verify their content?

HSBCMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
873

How would you design API test coverage for a new endpoint?

HSBCHard
Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
874

What is auto-waiting in Playwright?

HSBCEasy
Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
875

How do you set test timeouts?

HSBCMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
876

How do you use test.step and test annotations?

HSBCMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
877

How do you create test data through the API before a UI test?

HSBCHard
Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
878

How do you mock third-party APIs in UI tests?

HSBCMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
879

What are closures?

HSBCMedium
Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
880

What is npm and package.json?

HSBCEasy
Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
881

What are interfaces and types in TypeScript?

HSBCMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
882

How do you run Playwright in GitHub Actions?

HSBCMedium
Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
883

What are fixtures and how do you create a custom one?

HSBCMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
884

How do you run tests in parallel and control workers?

HSBCMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
885

What are arrow functions?

HSBCEasy
Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
886

Design a Playwright framework for a 500-test suite.

HSBCHard
Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
887

How do you handle token refresh in long API test runs?

HCLTechMedium
Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
888

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
889

How do you handle multiple tabs or pop-ups?

HCLTechMedium
Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
890

How do you handle date pickers and custom dropdowns?

HCLTechMedium
Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
891

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
892

How do you test a file download?

HCLTechMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
893

How do you handle iframes in Playwright?

HCLTechMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
894

How does visual testing work in Playwright?

HCLTechMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
895

Write an API test with the request fixture.

HCLTechMedium
Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
896

How do you share cookies between API login and UI?

HCLTechMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
897

How do you mock network requests?

HCLTechMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
898

How do you set test timeouts?

HCLTechMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
899

How do you combine API and UI tests?

HCLTechMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
900

What are global setup and teardown?

HCLTechMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
901

Which locators does Playwright recommend?

HCLTechMedium
Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
902

How do you shard tests across machines?

HCLTechMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
903

What is APIRequestContext?

HCLTechMedium
Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
904

How do you handle dialogs such as alerts?

HCLTechMedium
Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
905

How do you use test.step and test annotations?

HCLTechMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
906

How do you integrate Playwright with Allure or other reports?

HCLTechMedium
Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
907

How does Playwright's trace viewer help?

HCLTechMedium
Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
908

How do you mock an API response?

HCLTechMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
909

What is the difference between page, context and browser?

HCLTechMedium
Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
910

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
911

What is the difference between beforeEach and fixtures?

HCLTechMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
912

How do you run tests in Docker?

HCLTechMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
913

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
914

How do you perform drag and drop and hover?

HCLTechMedium
Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
915

What are fixtures and how do you create a custom one?

HCLTechMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
916

What is codegen?

HCLTechMedium
Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
917

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
918

What is the difference between synchronous and asynchronous code?

HCLTechMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
919

How do you test API error scenarios?

HCLTechMedium
Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
920

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
921

How do you run tests in parallel and control workers?

HCLTechMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
922

How do you test pagination or chained API calls?

HCLTechMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
923

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
924

Promise.all vs Promise.allSettled vs Promise.race?

HCLTechMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
925

How do you validate JSON schema?

HCLTechMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
926

How do you handle shadow DOM?

HCLTechMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
927

What is the difference between click and dispatchEvent?

Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
928

How do you run tests in Docker?

Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
929

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
930

How do you perform drag and drop and hover?

Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
931

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
932

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
933

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
934

How do you run tests in Docker?

Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
935

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
936

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
937

How do you do visual regression testing?

Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
938

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
939

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
940

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
941

How do you handle token refresh in long API test runs?

Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
942

How do you handle rate limits or slow APIs in tests?

Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
943

How do you structure environment-specific configs in Playwright?

Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
944

What is the difference between click and dispatchEvent?

Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
945

What is APIRequestContext?

Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
946

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
947

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
948

How do you handle authentication to avoid logging in every test?

Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
949

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
950

How do you send authentication headers?

Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
951

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
952

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
953

How do you debug a Playwright test?

Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
954

What happens if you forget an await?

Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
955

interface vs type in TypeScript?

Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
956

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
957

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
958

How do you perform drag and drop and hover?

Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
959

What is hoisting?

Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
960

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
961

What are closures?

Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
962

What are web-first assertions?

Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
963

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
964

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
965

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
966

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
967

How do you run tests on mobile viewports?

Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
968

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
969

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
970

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
971

How do you test a file download?

Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
972

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
973

How do you manage test data and environments?

Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
974

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
975

How do you test geolocation, permissions and time zones?

Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
976

How do you send a POST request with a JSON body?

Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
977

How do you handle shadow DOM?

Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
978

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
979

What does the optional chaining operator do?

Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
980

What is the difference between click and dispatchEvent?

Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
981

How do you structure environment-specific configs in Playwright?

Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
982

What are higher-order functions?

Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
983

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
984

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
985

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
986

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
987

How do you do visual regression testing?

Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
988

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
989

How do you handle token refresh in long API test runs?

Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
990

How do you handle rate limits or slow APIs in tests?

Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
991

Write an API test with the request fixture.

Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
992

What is the difference between map, filter and reduce?

Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
993

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
994

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
995

Promise.all vs Promise.allSettled vs Promise.race?

Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
996

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
997

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
998

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
999

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
1000

How do you run tests in parallel and control workers?

Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
1001

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
1002

What is the difference between null and undefined?

Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
1003

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
1004

How do you run tests on mobile viewports?

Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
1005

How do you test a file download?

Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
1006

What are generics in TypeScript?

Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
1007

How do you send authentication headers?

Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
1008

What are web-first assertions?

Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
1009

What happens if you forget an await?

Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
1010

How do you test geolocation, permissions and time zones?

Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
1011

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
1012

What are fixtures in Playwright?

Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
1013

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
1014

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
1015

How do you debug a Playwright test?

Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
1016

What is the difference between click and dispatchEvent?

Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
1017

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
1018

How do you mock network requests?

Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
1019

How do you set test timeouts?

Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
1020

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
1021

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
1022

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
1023

How do you run tests on mobile viewports?

Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
1024

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
1025

How do you integrate Playwright with Allure or other reports?

Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
1026

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
1027

How do you send authentication headers?

Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
1028

How do you perform drag and drop and hover?

Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
1029

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
1030

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
1031

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
1032

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
1033

How do you test geolocation, permissions and time zones?

Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
1034

What is hoisting?

Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
1035

How do you handle shadow DOM?

Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
1036

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
1037

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
1038

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
1039

How do you combine API and UI tests?

Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
1040

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
1041

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
1042

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
1043

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
1044

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
1045

How do you wait for a network response in Playwright?

Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
1046

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
1047

How do you handle date pickers and custom dropdowns?

Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
1048

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
1049

Which locators does Playwright recommend?

Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
1050

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
1051

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
1052

How do you run tests in parallel and control workers?

Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
1053

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
1054

How do you reuse login state across tests?

Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
1055

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
1056

What are global setup and teardown?

Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
1057

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
1058

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
1059

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
1060

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
1061

What is the difference between synchronous and asynchronous code?

Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
1062

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
1063

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
1064

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
1065

How do you send authentication headers?

Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
1066

How do you test geolocation, permissions and time zones?

Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
1067

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
1068

How do you handle token refresh in long API test runs?

Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
1069

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
1070

How do you integrate Playwright with Allure or other reports?

Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
1071

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
1072

What is hoisting?

Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
1073

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
1074

How do you send a POST request with a JSON body?

Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
1075

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
1076

What are closures?

Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
1077

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
1078

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
1079

How do you manage test data and environments?

Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
1080

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
1081

How do you mock network requests?

Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
1082

How do you do visual regression testing?

Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
1083

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
1084

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
1085

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
1086

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
1087

How do you test a file download?

Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
1088

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
1089

What reporters does Playwright provide?

Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
1090

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
1091

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
1092

How do you wait for a network response in Playwright?

Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
1093

How do you test pagination or chained API calls?

Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
1094

What is the difference between map, filter and reduce?

Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
1095

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
1096

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
1097

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
1098

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
1099

What are interfaces and types in TypeScript?

Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
1100

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
1101

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
1102

How do you manage test data and environments?

Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
1103

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
1104

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
1105

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
1106

What are closures?

Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
1107

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
1108

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
1109

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
1110

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
1111

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
1112

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
1113

How do you mock third-party APIs in UI tests?

Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
1114

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
1115

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
1116

What are soft assertions?

Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
1117

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
1118

How do you run Playwright in GitHub Actions?

Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
1119

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
1120

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
1121

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
1122

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
1123

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
1124

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
1125

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
1126

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
1127

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
1128

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
1129

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
1130

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
1131

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
1132

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
1133

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
1134

How do you send a POST request with a JSON body?

Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
1135

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
1136

How do you share cookies between API login and UI?

Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
1137

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
1138

What is the difference between click and dispatchEvent?

Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
1139

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
1140

How do you manage test data and environments?

Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
1141

How do you handle shadow DOM?

Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
1142

What is APIRequestContext?

Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
1143

What are soft assertions?

Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
1144

How do you mock network requests?

Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
1145

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
1146

How do you handle date pickers and custom dropdowns?

Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
1147

Which locators does Playwright recommend?

Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
1148

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
1149

How do you handle token refresh in long API test runs?

Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
1150

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
1151

How do you handle rate limits or slow APIs in tests?

Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
1152

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
1153

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
1154

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
1155

How do you handle authentication to avoid logging in every test?

Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
1156

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
1157

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
1158

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
1159

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
1160

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
1161

How do you run Playwright in GitHub Actions?

Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
1162

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
1163

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
1164

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
1165

What are fixtures in Playwright?

Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
1166

What are global setup and teardown?

Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
1167

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
1168

What happens if you forget an await?

Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
1169

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
1170

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
1171

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
1172

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
1173

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
1174

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
1175

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
1176

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
1177

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
1178

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
1179

How do you send a POST request with a JSON body?

Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
1180

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
1181

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
1182

What are fixtures in Playwright?

Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
1183

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
1184

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
1185

How do you handle token refresh in long API test runs?

Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
1186

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
1187

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
1188

How do you mock network requests?

Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
1189

What is the difference between synchronous and asynchronous code?

Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
1190

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
1191

How do you test a file download?

Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
1192

What is the difference between null and undefined?

Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
1193

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
1194

How do you manage test data and environments?

Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
1195

How do you wait for a network response in Playwright?

Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
1196

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
1197

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
1198

How do you reuse login state across tests?

Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
1199

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
1200

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
1201

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
1202

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
1203

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
1204

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
1205

What reporters does Playwright provide?

Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
1206

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
1207

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
1208

How do you send authentication headers?

Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
1209

Explain the event loop.

Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
1210

How do you do visual regression testing?

Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
1211

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
1212

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
1213

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
1214

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
1215

What does the optional chaining operator do?

Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
1216

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
1217

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
1218

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
1219

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
1220

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
1221

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
1222

How do you handle shadow DOM?

Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
1223

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
1224

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
1225

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
1226

How do you combine API and UI tests?

Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
1227

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
1228

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
1229

How do you manage test data and environments?

Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
1230

What are higher-order functions?

Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
1231

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
1232

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
1233

How do you set test timeouts?

Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
1234

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
1235

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
1236

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
1237

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
1238

What is APIRequestContext?

Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
1239

What is the difference between map, filter and reduce?

Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
1240

What is the difference between synchronous and asynchronous code?

Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
1241

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
1242

How do you send authentication headers?

Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
1243

How do you test geolocation, permissions and time zones?

Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
1244

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
1245

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
1246

How do you reuse login state across tests?

Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
1247

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
1248

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
1249

How do you handle date pickers and custom dropdowns?

Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
1250

How do you run tests on mobile viewports?

Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
1251

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
1252

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
1253

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
1254

What are interfaces and types in TypeScript?

Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
1255

How do you mock network requests?

Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
1256

How do you handle authentication to avoid logging in every test?

Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
1257

What is hoisting?

Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
1258

How do you perform drag and drop and hover?

Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
1259

What happens if you forget an await?

Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
1260

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
1261

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
1262

What are soft assertions?

Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
1263

Promise.all vs Promise.allSettled vs Promise.race?

Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
1264

How do you run tests in parallel and control workers?

Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
1265

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
1266

What is the difference between click and dispatchEvent?

Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
1267

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
1268

How do you test pagination or chained API calls?

Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
1269

How do you handle token refresh in long API test runs?

Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
1270

What is the difference between null and undefined?

Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
1271

What are closures?

Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
1272

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
1273

What are web-first assertions?

Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
1274

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
1275

How do you handle file uploads and downloads?

Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
1276

How do you mock an API response?

TCSMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
1277

How does Playwright's trace viewer help?

TCSMedium
Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
1278

Write an API test with the request fixture.

TCSMedium
Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
1279

How do you run tests in parallel and control workers?

TCSMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
1280

How do you run a single test or file in Playwright?

TCSEasy
Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
1281

How do you handle file uploads and downloads?

TCSMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
1282

What are arrow functions?

TCSEasy
Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
1283

How do you handle errors in async code?

TCSEasy
Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
1284

What does the optional chaining operator do?

TCSMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
1285

How would you handle a very flaky element that appears after an animation?

TCSHard
Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
1286

Explain the event loop.

TCSMedium
Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
1287

How do you share cookies between API login and UI?

TCSMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
1288

What are the main data types in JavaScript?

TCSEasy
Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
1289

How do you validate an API response in Playwright?

TCSMedium
Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
1290

How do you run only smoke tests?

TCSEasy
Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
1291

What are higher-order functions?

TCSMedium
Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
1292

How do you send authentication headers?

TCSMedium
Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
1293

How do you handle iframes in Playwright?

TCSMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
1294

What is the difference between click and dispatchEvent?

TCSMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
1295

How would you type the response of an API call in TypeScript?

TCSHard
Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
1296

What is the difference between API testing and UI testing?

TCSEasy
Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
1297

How do you combine API and UI tests?

TCSMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
1298

How do you run tests on mobile viewports?

TCSMedium
Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
1299

Which locators does Playwright recommend?

TCSMedium
Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
1300

How do you run tests in Docker?

TCSMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
1301

Tests are flaky in CI. How do you debug them?

TCSHard
Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
1302

How would you structure a large Playwright framework for a team?

TCSHard
Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
1303

How do you work with iframes?

TCSEasy
Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
1304

How does Playwright compare with Selenium and Cypress?

TCSMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
1305

How do you wait for a network response in Playwright?

TCSMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
1306

What is the difference between beforeEach and fixtures?

TCSMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
1307

What is Playwright and which browsers does it support?

TCSEasy
Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
1308

How do you write a Page Object in Playwright?

TCSEasy
Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
1309

How do you test accessibility with Playwright?

TCSMedium
Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
1310

How do you do visual regression testing?

TCSMedium
Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
1311

How do you take screenshots and videos?

TCSMedium
Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
1312

What happens if you forget an await?

TCSMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
1313

Design a Playwright framework for a 500-test suite.

TCSHard
Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
1314

How do you run tests on three browsers in parallel?

TCSEasy
Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
1315

How do you handle GraphQL APIs in Playwright?

TCSMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
1316

How do you mock third-party APIs in UI tests?

TCSMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
1317

How do you test a file download?

TCSMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
1318

What is npm and package.json?

TCSEasy
Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
1319

Locator vs ElementHandle?

TCSEasy
Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
1320

How do you validate JSON schema?

TCSMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
1321

What are interfaces and types in TypeScript?

TCSMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
1322

How do retries work?

TCSMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
1323

How do you handle dialogs such as alerts?

TCSMedium
Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
1324

How do you handle a new tab?

TCSEasy
Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
1325

What is a locator in Playwright?

TCSEasy
Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
1326

Write a test that logs in and checks the dashboard heading.

TCSEasy
Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
1327

What is hoisting?

TCSMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
1328

How do you handle token refresh in long API test runs?

TCSMedium
Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
1329

What is the difference between synchronous and asynchronous code?

TCSMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
1330

How do you organise tests with page object model in Playwright?

TCSMedium
Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
1331

How do you handle authentication to avoid logging in every test?

TCSMedium
Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
1332

What is async/await?

TCSEasy
Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
1333

What is the difference between a type and an enum in TypeScript?

TCSMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
1334

What is the difference between page, context and browser?

TCSMedium
Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
1335

What is APIRequestContext?

TCSMedium
Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
1336

How do you test file upload via API?

TCSMedium
Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
1337

Promise.all vs Promise.allSettled vs Promise.race?

TCSMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
1338

What are template literals?

TCSMedium
Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
1339

How does visual testing work in Playwright?

TCSMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
1340

How do you shard tests across machines?

TCSMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
1341

How do you tag and filter tests?

TCSMedium
Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
1342

What are fixtures and how do you create a custom one?

TCSMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
1343

How do you handle rate limits or slow APIs in tests?

TCSMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
1344

What are closures?

TCSMedium
Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
1345

How do you combine API and UI tests?

InfosysMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
1346

How do you run tests on mobile viewports?

InfosysMedium
Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
1347

How do you share cookies between API login and UI?

InfosysMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
1348

Promise.all vs Promise.allSettled vs Promise.race?

InfosysMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
1349

How does Playwright compare with Selenium and Cypress?

InfosysMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
1350

How do you test file upload via API?

InfosysMedium
Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
1351

What are projects in playwright.config?

InfosysMedium
Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
1352

What are web-first assertions?

InfosysMedium
Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
1353

interface vs type in TypeScript?

InfosysMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
1354

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
1355

What are fixtures and how do you create a custom one?

InfosysMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
1356

How do you handle shadow DOM?

InfosysMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
1357

How do you manage test data and environments?

InfosysMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
1358

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
1359

What is the difference between synchronous and asynchronous code?

InfosysMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
1360

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
1361

What is the difference between map, filter and reduce?

InfosysMedium
Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
1362

What is hoisting?

InfosysMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
1363

What is the difference between click and dispatchEvent?

InfosysMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
1364

What are interfaces and types in TypeScript?

InfosysMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
1365

How do you use test.step and test annotations?

InfosysMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
1366

What is destructuring and the spread operator?

InfosysMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
1367

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
1368

How do retries work?

InfosysMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
1369

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
1370

How do you validate JSON schema?

InfosysMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
1371

How do you handle date pickers and custom dropdowns?

InfosysMedium
Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
1372

What is codegen?

InfosysMedium
Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
1373

How do you shard tests across machines?

InfosysMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
1374

How do you reuse login state across tests?

InfosysMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
1375

How do you integrate Playwright with Allure or other reports?

InfosysMedium
Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
1376

How do you test accessibility with Playwright?

InfosysMedium
Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
1377

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
1378

How do you run tests in Docker?

InfosysMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
1379

What happens if you forget an await?

InfosysMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
1380

What are fixtures and how do you create a custom one?

WiproMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
1381

How do you use test.step and test annotations?

WiproMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
1382

What is async/await?

WiproEasy
Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
1383

How would you design API test coverage for a new endpoint?

WiproHard
Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
1384

What is the difference between map, filter and reduce?

WiproMedium
Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
1385

Write a test that logs in and checks the dashboard heading.

WiproEasy
Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
1386

How do you handle date pickers and custom dropdowns?

WiproMedium
Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
1387

How do retries work?

WiproMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
1388

What are web-first assertions?

WiproMedium
Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
1389

Locator vs ElementHandle?

WiproEasy
Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
1390

How do you handle a new tab?

WiproEasy
Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
1391

How do you test API error scenarios?

WiproMedium
Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
1392

How do you send a POST request with a JSON body?

WiproMedium
Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
1393

What are generics in TypeScript?

WiproMedium
Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
1394

How do you manage test data and environments?

WiproMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
1395

How do you handle errors in async code?

WiproEasy
Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
1396

What is auto-waiting in Playwright?

WiproEasy
Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
1397

How do you structure environment-specific configs in Playwright?

WiproMedium
Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
1398

What is npm and package.json?

WiproEasy
Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
1399

What is a locator in Playwright?

WiproEasy
Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
1400

How do you share cookies between API login and UI?

WiproMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
1401

How do you shard tests across machines?

WiproMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
1402

How do you mock network requests?

WiproMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
1403

What are projects in playwright.config?

WiproMedium
Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
1404

How do you set test timeouts?

WiproMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
1405

How do you measure API response time?

WiproMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
1406

How do you reduce the execution time of a 2000-test suite?

WiproHard
Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
1407

How do you test accessibility with Playwright?

WiproMedium
Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
1408

How do you write a Page Object in Playwright?

WiproEasy
Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
1409

How does Playwright's trace viewer help?

WiproMedium
Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
1410

What is the difference between page, context and browser?

WiproMedium
Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
1411

How do you install and start a Playwright project?

WiproEasy
Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
1412

How do you handle authentication to avoid logging in every test?

WiproMedium
Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
1413

What are interfaces and types in TypeScript?

WiproMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
1414

How do you handle multiple tabs or pop-ups?

WiproMedium
Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
1415

What are closures?

WiproMedium
Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
1416

How do you make an API request in Playwright?

WiproEasy
Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
1417

What does the optional chaining operator do?

WiproMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
1418

What is the difference between null and undefined?

WiproMedium
Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
1419

How do you handle shadow DOM?

WiproMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
1420

How would you structure a large Playwright framework for a team?

WiproHard
Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
1421

How do you debug a Playwright test?

WiproMedium
Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
1422

How do you organise tests with page object model in Playwright?

WiproMedium
Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
1423

Promise.all vs Promise.allSettled vs Promise.race?

WiproMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
1424

Explain the event loop.

WiproMedium
Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
1425

What are arrow functions?

WiproEasy
Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
1426

What is the difference between API testing and UI testing?

WiproEasy
Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
1427

Why choose Playwright over Selenium?

WiproMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
1428

How do you run a single test or file in Playwright?

WiproEasy
Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
1429

How do you perform drag and drop and hover?

WiproMedium
Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
1430

What are global setup and teardown?

WiproMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
1431

How do you send a POST request with a JSON body?

Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
1432

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
1433

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
1434

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
1435

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
1436

How do you debug a Playwright test?

Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
1437

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
1438

How do you test geolocation, permissions and time zones?

Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
1439

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
1440

What is the difference between null and undefined?

Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
1441

What are closures?

Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
1442

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
1443

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
1444

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
1445

What is the difference between click and dispatchEvent?

Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
1446

What are fixtures in Playwright?

Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
1447

What are interfaces and types in TypeScript?

Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
1448

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
1449

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
1450

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
1451

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
1452

What is the difference between map, filter and reduce?

Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
1453

What are web-first assertions?

Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
1454

How do you send authentication headers?

Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
1455

How do you handle token refresh in long API test runs?

Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
1456

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
1457

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
1458

How do you combine API and UI tests?

Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
1459

Write an API test with the request fixture.

Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
1460

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
1461

How do you test a file download?

Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
1462

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
1463

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
1464

How do you handle file uploads and downloads?

Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
1465

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
1466

How do you perform drag and drop and hover?

Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
1467

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
1468

How do you run tests in Docker?

Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
1469

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
1470

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
1471

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
1472

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
1473

How do you integrate Playwright with Allure or other reports?

Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
1474

How do you manage test data and environments?

Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
1475

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
1476

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
1477

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
1478

What is APIRequestContext?

Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
1479

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
1480

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
1481

How do you run Playwright in GitHub Actions?

Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
1482

Which locators does Playwright recommend?

Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
1483

What are soft assertions?

Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
1484

What reporters does Playwright provide?

Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
1485

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
1486

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
1487

What is the difference between map, filter and reduce?

Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
1488

What is the difference between null and undefined?

Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
1489

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
1490

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
1491

What does the optional chaining operator do?

Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
1492

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
1493

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
1494

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
1495

How do you test pagination or chained API calls?

Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
1496

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
1497

How do you handle date pickers and custom dropdowns?

Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
1498

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
1499

How do you handle shadow DOM?

Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
1500

How do you manage test data and environments?

Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
1501

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
1502

What are soft assertions?

Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
1503

What are closures?

Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
1504

How do you combine API and UI tests?

Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
1505

What are interfaces and types in TypeScript?

Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
1506

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
1507

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
1508

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
1509

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
1510

How do you handle file uploads and downloads?

Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
1511

How do you handle rate limits or slow APIs in tests?

Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
1512

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
1513

Write an API test with the request fixture.

Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
1514

Which locators does Playwright recommend?

Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
1515

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
1516

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
1517

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
1518

How do you structure environment-specific configs in Playwright?

Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
1519

How do you do visual regression testing?

Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
1520

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
1521

What is the difference between synchronous and asynchronous code?

Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
1522

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
1523

How do you integrate Playwright with Allure or other reports?

Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
1524

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
1525

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
1526

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
1527

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
1528

Promise.all vs Promise.allSettled vs Promise.race?

Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
1529

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
1530

How do you debug a Playwright test?

Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
1531

How do you handle token refresh in long API test runs?

Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
1532

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
1533

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
1534

How do you handle authentication to avoid logging in every test?

Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
1535

What are global setup and teardown?

Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
1536

How do you send a POST request with a JSON body?

Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
1537

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
1538

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
1539

What happens if you forget an await?

Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
1540

What is the difference between synchronous and asynchronous code?

Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
1541

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
1542

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
1543

How do you test geolocation, permissions and time zones?

Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
1544

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
1545

interface vs type in TypeScript?

Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
1546

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
1547

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
1548

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
1549

How do you handle shadow DOM?

Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
1550

What are global setup and teardown?

Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
1551

What is APIRequestContext?

Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
1552

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
1553

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
1554

What happens if you forget an await?

Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
1555

What are closures?

Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
1556

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
1557

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
1558

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
1559

How do you send authentication headers?

Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
1560

What is the difference between click and dispatchEvent?

Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
1561

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
1562

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
1563

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
1564

How do you run Playwright in GitHub Actions?

Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
1565

How do you share cookies between API login and UI?

Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
1566

How do you combine API and UI tests?

Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
1567

How do you debug a Playwright test?

Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
1568

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
1569

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
1570

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
1571

What are interfaces and types in TypeScript?

Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
1572

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
1573

Explain the event loop.

Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
1574

What does the optional chaining operator do?

Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
1575

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
1576

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
1577

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
1578

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
1579

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
1580

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
1581

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
1582

How do you handle authentication to avoid logging in every test?

DeloitteMedium
Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
1583

How do you validate JSON schema?

DeloitteMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
1584

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
1585

What happens if you forget an await?

DeloitteMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
1586

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
1587

How do you combine API and UI tests?

DeloitteMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
1588

How do you handle token refresh in long API test runs?

DeloitteMedium
Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
1589

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
1590

How do you run tests in parallel and control workers?

DeloitteMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
1591

How do you shard tests across machines?

DeloitteMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
1592

What is APIRequestContext?

DeloitteMedium
Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
1593

What are fixtures and how do you create a custom one?

DeloitteMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
1594

How do you test pagination or chained API calls?

DeloitteMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
1595

How do retries work?

DeloitteMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
1596

How do you handle iframes in Playwright?

DeloitteMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
1597

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
1598

How do you handle dialogs such as alerts?

DeloitteMedium
Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
1599

How do you wait for a network response in Playwright?

DeloitteMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
1600

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
1601

How do you debug a Playwright test?

DeloitteMedium
Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
1602

What are fixtures in Playwright?

DeloitteMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
1603

How do you set test timeouts?

DeloitteMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
1604

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
1605

How do you send authentication headers?

DeloitteMedium
Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
1606

interface vs type in TypeScript?

DeloitteMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
1607

What is the difference between waitForSelector and expect with locator?

DeloitteMedium
Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
1608

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
1609

Which locators does Playwright recommend?

DeloitteMedium
Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
1610

How do you measure API response time?

DeloitteMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
1611

How do you test file downloads and verify their content?

DeloitteMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
1612

What are web-first assertions?

DeloitteMedium
Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
1613

Why choose Playwright over Selenium?

DeloitteMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
1614

How do you test file upload via API?

DeloitteMedium
Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
1615

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
1616

How do you run tests in Docker?

DeloitteMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
1617

How do you mock an API response?

DeloitteMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
1618

How do you mock network requests?

DeloitteMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
1619

How do you do visual regression testing?

DeloitteMedium
Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
1620

What is the difference between synchronous and asynchronous code?

DeloitteMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
1621

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
1622

Write an API test with the request fixture.

DeloitteMedium
Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
1623

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
1624

How do you test accessibility with Playwright?

DeloitteMedium
Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
1625

How do you test a file download?

DeloitteMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
1626

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
1627

What are generics in TypeScript?

DeloitteMedium
Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
1628

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
1629

How do you handle shadow DOM?

DeloitteMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
1630

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
1631

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
1632

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
1633

How do you handle GraphQL APIs in Playwright?

DeloitteMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
1634

How does Playwright's trace viewer help?

DeloitteMedium
Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
1635

What is destructuring and the spread operator?

DeloitteMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
1636

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
1637

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
1638

How do you tag and filter tests?

DeloitteMedium
Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
1639

What are template literals?

DeloitteMedium
Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
1640

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
1641

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
1642

How do you take screenshots and videos?

DeloitteMedium
Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
1643

How do you test geolocation, permissions and time zones?

DeloitteMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
1644

How do you reuse login state across tests?

DeloitteMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
1645

What are soft assertions?

DeloitteMedium
Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
1646

How do you run tests on mobile viewports?

DeloitteMedium
Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
1647

What is hoisting?

DeloitteMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
1648

What is the difference between page, context and browser?

AmazonMedium
Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
1649

How do you run Playwright in GitHub Actions?

AmazonMedium
Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
1650

Write an API test with the request fixture.

AmazonMedium
Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
1651

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
1652

What happens if you forget an await?

AmazonMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
1653

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
1654

How do you mock third-party APIs in UI tests?

AmazonMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
1655

What is destructuring and the spread operator?

AmazonMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
1656

How do you handle GraphQL APIs in Playwright?

AmazonMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
1657

What are generics in TypeScript?

AmazonMedium
Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
1658

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
1659

How do you run tests on mobile viewports?

AmazonMedium
Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
1660

How do you test file upload via API?

AmazonMedium
Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
1661

How do you measure API response time?

AmazonMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
1662

How do you handle dialogs such as alerts?

AmazonMedium
Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
1663

What reporters does Playwright provide?

AmazonMedium
Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
1664

How do you test accessibility with Playwright?

AmazonMedium
Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
1665

What is the difference between null and undefined?

AmazonMedium
Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
1666

What are global setup and teardown?

AmazonMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
1667

How do you validate an API response in Playwright?

AmazonMedium
Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
1668

How do you use test.step and test annotations?

AmazonMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
1669

What are fixtures and how do you create a custom one?

AmazonMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
1670

How do you send authentication headers?

AmazonMedium
Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
1671

Which locators does Playwright recommend?

AmazonMedium
Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
1672

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
1673

How do you debug a Playwright test?

AmazonMedium
Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
1674

How do you test a file download?

AmazonMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
1675

How do you test geolocation, permissions and time zones?

AmazonMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
1676

How do you do visual regression testing?

AmazonMedium
Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
1677

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
1678

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
1679

How do you handle token refresh in long API test runs?

AmazonMedium
Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
1680

What is the difference between map, filter and reduce?

AmazonMedium
Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
1681

How do retries work?

AmazonMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
1682

How do you share cookies between API login and UI?

AmazonMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
1683

What is the difference between beforeEach and fixtures?

AmazonMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
1684

How does Playwright compare with Selenium and Cypress?

AmazonMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
1685

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
1686

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
1687

How does visual testing work in Playwright?

AmazonMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
1688

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
1689

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
1690

How do you handle iframes in Playwright?

AmazonMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
1691

How do you organise tests with page object model in Playwright?

AmazonMedium
Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
1692

How do you test API error scenarios?

AmazonMedium
Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
1693

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
1694

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
1695

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
1696

Why choose Playwright over Selenium?

AmazonMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
1697

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
1698

How do you run tests in parallel and control workers?

AmazonMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
1699

How do you run tests in Docker?

AmazonMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
1700

What is hoisting?

AmazonMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
1701

How do you handle authentication to avoid logging in every test?

AmazonMedium
Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
1702

How do you shard tests across machines?

AmazonMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
1703

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
1704

What is the difference between click and dispatchEvent?

AmazonMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
1705

What are template literals?

AmazonMedium
Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
1706

What are interfaces and types in TypeScript?

AmazonMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
1707

How do you mock network requests?

AmazonMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
1708

How do you test file downloads and verify their content?

AmazonMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
1709

How do you tag and filter tests?

AmazonMedium
Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
1710

What are higher-order functions?

AmazonMedium
Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
1711

How do you handle date pickers and custom dropdowns?

GoogleMedium
Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
1712

What is the difference between page, context and browser?

GoogleMedium
Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
1713

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
1714

How do you validate JSON schema?

GoogleMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
1715

Which locators does Playwright recommend?

GoogleMedium
Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
1716

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
1717

What is the difference between a type and an enum in TypeScript?

GoogleMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
1718

How do you mock an API response?

GoogleMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
1719

How do you send a POST request with a JSON body?

GoogleMedium
Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
1720

What are higher-order functions?

GoogleMedium
Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
1721

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
1722

How do you test a file download?

GoogleMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
1723

What is the difference between waitForSelector and expect with locator?

GoogleMedium
Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
1724

What is destructuring and the spread operator?

GoogleMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
1725

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
1726

How do you test file downloads and verify their content?

GoogleMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
1727

How do you handle authentication to avoid logging in every test?

GoogleMedium
Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
1728

How do you structure environment-specific configs in Playwright?

GoogleMedium
Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
1729

interface vs type in TypeScript?

GoogleMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
1730

How do you run tests on mobile viewports?

GoogleMedium
Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
1731

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
1732

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
1733

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
1734

How do you combine API and UI tests?

GoogleMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
1735

How do you handle dialogs such as alerts?

GoogleMedium
Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
1736

What are web-first assertions?

GoogleMedium
Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
1737

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
1738

How do you run tests in parallel and control workers?

GoogleMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
1739

How do you test pagination or chained API calls?

GoogleMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
1740

How do you test geolocation, permissions and time zones?

GoogleMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
1741

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
1742

How do you measure API response time?

GoogleMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
1743

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
1744

What is APIRequestContext?

GoogleMedium
Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
1745

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
1746

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
1747

What are projects in playwright.config?

GoogleMedium
Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
1748

How do you handle multiple tabs or pop-ups?

GoogleMedium
Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
1749

What is the difference between synchronous and asynchronous code?

GoogleMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
1750

What is the difference between map, filter and reduce?

GoogleMedium
Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
1751

How do you handle iframes in Playwright?

GoogleMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
1752

What is the difference between click and dispatchEvent?

GoogleMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
1753

How do you use test.step and test annotations?

GoogleMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
1754

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
1755

What are soft assertions?

GoogleMedium
Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
1756

What are template literals?

GoogleMedium
Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
1757

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
1758

interface vs type in TypeScript?

MetaMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
1759

How do you validate JSON schema?

MetaMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
1760

Design a Playwright framework for a 500-test suite.

MetaHard
Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
1761

How do you do visual regression testing?

MetaMedium
Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
1762

What is the difference between waitForSelector and expect with locator?

MetaMedium
Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
1763

How does Playwright compare with Selenium and Cypress?

MetaMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
1764

Tests are flaky in CI. How do you debug them?

MetaHard
Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
1765

What is APIRequestContext?

MetaMedium
Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
1766

Explain the event loop.

MetaMedium
Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
1767

What are projects in playwright.config?

MetaMedium
Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
1768

What is the difference between map, filter and reduce?

MetaMedium
Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
1769

What is the difference between a type and an enum in TypeScript?

MetaMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
1770

What is codegen?

MetaMedium
Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
1771

How do you run a single test or file in Playwright?

MetaEasy
Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
1772

How do you handle a new tab?

MetaEasy
Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
1773

What are closures?

MetaMedium
Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
1774

How do you handle GraphQL APIs in Playwright?

MetaMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
1775

How do you validate an API response in Playwright?

MetaMedium
Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
1776

How do retries work?

MetaMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
1777

What is Playwright and which browsers does it support?

MetaEasy
Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
1778

What is the difference between synchronous and asynchronous code?

MetaMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
1779

How do you mock third-party APIs in UI tests?

MetaMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
1780

What are global setup and teardown?

MetaMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
1781

What happens if you forget an await?

MetaMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
1782

How do you handle rate limits or slow APIs in tests?

MetaMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
1783

What does the optional chaining operator do?

MetaMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
1784

How do you use test.step and test annotations?

MetaMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
1785

Locator vs ElementHandle?

MetaEasy
Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
1786

How do you test file downloads and verify their content?

MetaMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
1787

How do you run tests in parallel and control workers?

MetaMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
1788

What is destructuring and the spread operator?

MetaMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
1789

How do you handle date pickers and custom dropdowns?

MetaMedium
Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
1790

What are soft assertions?

MetaMedium
Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
1791

What is hoisting?

MetaMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
1792

How do you handle token refresh in long API test runs?

MetaMedium
Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
1793

let vs const vs var?

MetaEasy
Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
1794

How do you manage test data and environments?

MetaMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
1795

How do you handle shadow DOM?

MetaMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
1796

How do you mock an API response?

MetaMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
1797

How do you send a POST request with a JSON body?

MetaMedium
Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
1798

How would you handle a very flaky element that appears after an animation?

MetaHard
Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
1799

What are template literals?

MetaMedium
Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
1800

What are the main data types in JavaScript?

MetaEasy
Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
1801

What are fixtures and how do you create a custom one?

MetaMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
1802

How do you test geolocation, permissions and time zones?

MetaMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
1803

What is the difference between null and undefined?

MetaMedium
Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
1804

How do you mock network requests?

MetaMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
1805

Why choose Playwright over Selenium?

MetaMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
1806

How do you reuse login state across tests?

MetaMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
1807

How do you integrate Playwright with Allure or other reports?

MetaMedium
Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
1808

Write an API test with the request fixture.

MetaMedium
Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
1809

What is auto-waiting in Playwright?

MetaEasy
Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
1810

How do you test a file download?

MetaMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
1811

How do you share cookies between API login and UI?

MetaMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
1812

What does the optional chaining operator do?

Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
1813

How do you run tests on mobile viewports?

Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
1814

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
1815

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
1816

How do you integrate Playwright with Allure or other reports?

Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
1817

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
1818

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
1819

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
1820

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
1821

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
1822

How do you handle rate limits or slow APIs in tests?

Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
1823

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
1824

How do you structure environment-specific configs in Playwright?

Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
1825

What are closures?

Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
1826

How do you debug a Playwright test?

Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
1827

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
1828

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
1829

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
1830

What are higher-order functions?

Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
1831

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
1832

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
1833

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
1834

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
1835

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
1836

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
1837

How do you run tests in Docker?

Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
1838

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
1839

How do you perform drag and drop and hover?

Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
1840

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
1841

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
1842

How do you handle file uploads and downloads?

Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
1843

Which locators does Playwright recommend?

Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
1844

How do you handle shadow DOM?

Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
1845

What is hoisting?

Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
1846

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
1847

How do you set test timeouts?

Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
1848

How do you send a POST request with a JSON body?

Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
1849

How do you handle authentication to avoid logging in every test?

Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
1850

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
1851

Promise.all vs Promise.allSettled vs Promise.race?

Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
1852

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
1853

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
1854

What is the difference between click and dispatchEvent?

Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
1855

How do you handle date pickers and custom dropdowns?

Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
1856

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
1857

What are generics in TypeScript?

Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
1858

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
1859

What is the difference between null and undefined?

Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
1860

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
1861

How do you mock third-party APIs in UI tests?

Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
1862

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
1863

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
1864

interface vs type in TypeScript?

Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
1865

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
1866

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
1867

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
1868

What reporters does Playwright provide?

Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
1869

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
1870

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
1871

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
1872

What are global setup and teardown?

Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
1873

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
1874

What are global setup and teardown?

AppleMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
1875

How does Playwright compare with Selenium and Cypress?

AppleMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
1876

What is the difference between page, context and browser?

AppleMedium
Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
1877

How do you validate JSON schema?

AppleMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
1878

How do you reduce the execution time of a 2000-test suite?

AppleHard
Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
1879

How do you take screenshots and videos?

AppleMedium
Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
1880

What does the optional chaining operator do?

AppleMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
1881

How do you handle GraphQL APIs in Playwright?

AppleMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
1882

How do you structure environment-specific configs in Playwright?

AppleMedium
Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
1883

How do you run Playwright in GitHub Actions?

AppleMedium
Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
1884

How do you run tests in Docker?

AppleMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
1885

Promise.all vs Promise.allSettled vs Promise.race?

AppleMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
1886

How do you write a Page Object in Playwright?

AppleEasy
Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
1887

Design a Playwright framework for a 500-test suite.

AppleHard
Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
1888

How do you test geolocation, permissions and time zones?

AppleMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
1889

How do you test API error scenarios?

AppleMedium
Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
1890

How do you handle a new tab?

AppleEasy
Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
1891

What is the difference between waitForSelector and expect with locator?

AppleMedium
Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
1892

Write an API test with the request fixture.

AppleMedium
Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
1893

let vs const vs var?

AppleEasy
Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
1894

What happens if you forget an await?

AppleMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
1895

Why choose Playwright over Selenium?

AppleMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
1896

Tests are flaky in CI. How do you debug them?

AppleHard
Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
1897

What is the difference between null and undefined?

AppleMedium
Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
1898

How do you debug a Playwright test?

AppleMedium
Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
1899

How do you shard tests across machines?

AppleMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
1900

What is npm and package.json?

AppleEasy
Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
1901

interface vs type in TypeScript?

AppleMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
1902

What is destructuring and the spread operator?

AppleMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
1903

How do you run only smoke tests?

AppleEasy
Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
1904

How do you set test timeouts?

AppleMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
1905

What are the main data types in JavaScript?

AppleEasy
Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
1906

What is the difference between TypeScript and JavaScript?

AppleEasy
Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
1907

How do you send a POST request with a JSON body?

AppleMedium
Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
1908

What reporters does Playwright provide?

AppleMedium
Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
1909

How do you test file downloads and verify their content?

AppleMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
1910

How do you share cookies between API login and UI?

AppleMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
1911

What is hoisting?

AppleMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
1912

How do you handle iframes in Playwright?

AppleMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
1913

How do retries work?

AppleMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
1914

What is the difference between map, filter and reduce?

AppleMedium
Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
1915

How do you handle errors in async code?

AppleEasy
Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
1916

How do you mock an API response?

AppleMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
1917

How would you design API test coverage for a new endpoint?

AppleHard
Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
1918

Locator vs ElementHandle?

AppleEasy
Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
1919

How do you test file upload via API?

AppleMedium
Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
1920

How do you wait for a network response in Playwright?

AppleMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
1921

How do you handle shadow DOM?

AppleMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
1922

What is the difference between a type and an enum in TypeScript?

AppleMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
1923

Which locators does Playwright recommend?

AppleMedium
Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
1924

How do you use test.step and test annotations?

AppleMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
1925

How do you handle rate limits or slow APIs in tests?

AppleMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
1926

How do you test a file download?

AppleMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
1927

How do you manage test data and environments?

AppleMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
1928

What is the difference between API testing and UI testing?

AppleEasy
Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
1929

How do you make an API request in Playwright?

AppleEasy
Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
1930

What are fixtures in Playwright?

AppleMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
1931

How do you handle dialogs such as alerts?

AppleMedium
Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
1932

How do you handle token refresh in long API test runs?

LinkedInMedium
Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
1933

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
1934

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
1935

How do you handle GraphQL APIs in Playwright?

LinkedInMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
1936

How do you run tests in parallel and control workers?

LinkedInMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
1937

How do you handle dialogs such as alerts?

LinkedInMedium
Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
1938

Why choose Playwright over Selenium?

LinkedInMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
1939

How do you handle date pickers and custom dropdowns?

LinkedInMedium
Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
1940

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
1941

How do you handle file uploads and downloads?

LinkedInMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
1942

How do you run tests on mobile viewports?

LinkedInMedium
Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
1943

How do you handle rate limits or slow APIs in tests?

LinkedInMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
1944

What happens if you forget an await?

LinkedInMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
1945

How do you handle shadow DOM?

LinkedInMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
1946

How do you test accessibility with Playwright?

LinkedInMedium
Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
1947

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
1948

How do you organise tests with page object model in Playwright?

LinkedInMedium
Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
1949

What is destructuring and the spread operator?

LinkedInMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
1950

Write an API test with the request fixture.

LinkedInMedium
Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
1951

What is the difference between beforeEach and fixtures?

LinkedInMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
1952

How do you run tests in Docker?

LinkedInMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
1953

What is the difference between null and undefined?

LinkedInMedium
Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
1954

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
1955

What is the difference between a type and an enum in TypeScript?

LinkedInMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
1956

How does Playwright compare with Selenium and Cypress?

LinkedInMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
1957

How do you measure API response time?

LinkedInMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
1958

What are generics in TypeScript?

LinkedInMedium
Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
1959

What are projects in playwright.config?

LinkedInMedium
Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
1960

What are soft assertions?

LinkedInMedium
Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
1961

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
1962

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
1963

How do you test file downloads and verify their content?

LinkedInMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
1964

How do you reuse login state across tests?

LinkedInMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
1965

What is the difference between map, filter and reduce?

LinkedInMedium
Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
1966

How do you take screenshots and videos?

LinkedInMedium
Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
1967

How do you use test.step and test annotations?

LinkedInMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
1968

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
1969

How does visual testing work in Playwright?

LinkedInMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
1970

What are interfaces and types in TypeScript?

LinkedInMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
1971

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
1972

What is the difference between synchronous and asynchronous code?

LinkedInMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
1973

How do you mock network requests?

LinkedInMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
1974

What reporters does Playwright provide?

LinkedInMedium
Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
1975

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
1976

How do you do visual regression testing?

LinkedInMedium
Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
1977

How do you share cookies between API login and UI?

LinkedInMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
1978

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
1979

What are fixtures in Playwright?

LinkedInMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
1980

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
1981

Explain the event loop.

LinkedInMedium
Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
1982

How do you debug a Playwright test?

LinkedInMedium
Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
1983

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
1984

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
1985

How do you structure environment-specific configs in Playwright?

LinkedInMedium
Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
1986

How do you handle iframes in Playwright?

LinkedInMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
1987

What is codegen?

LinkedInMedium
Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
1988

How do you mock third-party APIs in UI tests?

LinkedInMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
1989

How do you shard tests across machines?

LinkedInMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
1990

How do you validate an API response in Playwright?

LinkedInMedium
Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
1991

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
1992

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
1993

What is the difference between null and undefined?

Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
1994

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
1995

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
1996

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
1997

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
1998

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
1999

What is the difference between synchronous and asynchronous code?

Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
2000

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
2001

How do you set test timeouts?

Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
2002

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
2003

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
2004

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
2005

Write an API test with the request fixture.

Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
2006

How do you debug a Playwright test?

Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
2007

How do you test pagination or chained API calls?

Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
2008

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
2009

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
2010

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
2011

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
2012

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
2013

How do you run tests in Docker?

Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
2014

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
2015

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
2016

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
2017

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
2018

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
2019

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
2020

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
2021

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
2022

How do you combine API and UI tests?

Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
2023

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
2024

How do you mock network requests?

Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
2025

What are higher-order functions?

Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
2026

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
2027

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
2028

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
2029

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
2030

How do you structure environment-specific configs in Playwright?

Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
2031

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
2032

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
2033

Which locators does Playwright recommend?

Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
2034

Explain the event loop.

Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
2035

What are web-first assertions?

Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
2036

What are web-first assertions?

UberMedium
Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
2037

What is destructuring and the spread operator?

UberMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
2038

What is the difference between null and undefined?

UberMedium
Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
2039

How do you manage test data and environments?

UberMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
2040

What is npm and package.json?

UberEasy
Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
2041

How do you handle a new tab?

UberEasy
Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
2042

How do you validate an API response in Playwright?

UberMedium
Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
2043

How do you measure API response time?

UberMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
2044

What is the difference between synchronous and asynchronous code?

UberMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
2045

What are higher-order functions?

UberMedium
Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
2046

How do you handle token refresh in long API test runs?

UberMedium
Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
2047

What is a locator in Playwright?

UberEasy
Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
2048

How do you set test timeouts?

UberMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
2049

What are fixtures and how do you create a custom one?

UberMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
2050

What are template literals?

UberMedium
Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
2051

How do you structure environment-specific configs in Playwright?

UberMedium
Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
2052

How do you shard tests across machines?

UberMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
2053

How do you integrate Playwright with Allure or other reports?

UberMedium
Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
2054

interface vs type in TypeScript?

UberMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
2055

Tests are flaky in CI. How do you debug them?

UberHard
Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
2056

Locator vs ElementHandle?

UberEasy
Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
2057

How do you reuse login state across tests?

UberMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
2058

How would you structure a large Playwright framework for a team?

UberHard
Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
2059

What is Playwright and which browsers does it support?

UberEasy
Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
2060

How do you create test data through the API before a UI test?

UberHard
Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
2061

What are soft assertions?

UberMedium
Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
2062

How do you test file downloads and verify their content?

UberMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
2063

Design a Playwright framework for a 500-test suite.

UberHard
Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
2064

What does the optional chaining operator do?

UberMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
2065

How do you handle rate limits or slow APIs in tests?

UberMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
2066

How do you work with iframes?

UberEasy
Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
2067

What is the difference between click and dispatchEvent?

UberMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
2068

How do you do visual regression testing?

UberMedium
Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
2069

What are global setup and teardown?

UberMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
2070

What is the difference between a type and an enum in TypeScript?

UberMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
2071

How do you test a file download?

UberMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
2072

How do you handle iframes in Playwright?

UberMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
2073

How do you handle file uploads and downloads?

UberMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
2074

What is the difference between API testing and UI testing?

UberEasy
Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
2075

How do you run tests in Docker?

UberMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
2076

How do you mock third-party APIs in UI tests?

UberMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
2077

How do you run tests on three browsers in parallel?

UberEasy
Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
2078

How would you design API test coverage for a new endpoint?

UberHard
Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
2079

How do you send a POST request with a JSON body?

UberMedium
Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
2080

How do you use test.step and test annotations?

UberMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
2081

What is async/await?

UberEasy
Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
2082

How do you mock an API response?

UberMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
2083

How do you write a Page Object in Playwright?

UberEasy
Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
2084

How do you mock network requests?

UberMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
2085

What are arrow functions?

UberEasy
Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
2086

Promise.all vs Promise.allSettled vs Promise.race?

UberMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
2087

What happens if you forget an await?

UberMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
2088

Write a test that logs in and checks the dashboard heading.

UberEasy
Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
2089

What is APIRequestContext?

UberMedium
Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
2090

How do you send authentication headers?

UberMedium
Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
2091

How do you validate JSON schema?

UberMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
2092

How do you test accessibility with Playwright?

UberMedium
Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
2093

How do you run Playwright in GitHub Actions?

UberMedium
Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
2094

How do you test pagination or chained API calls?

UberMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
2095

What are the main data types in JavaScript?

UberEasy
Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
2096

What are projects in playwright.config?

UberMedium
Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
2097

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
2098

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
2099

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
2100

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
2101

Which locators does Playwright recommend?

Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
2102

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
2103

How do you manage test data and environments?

Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
2104

How do you run tests on mobile viewports?

Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
2105

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
2106

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
2107

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
2108

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
2109

interface vs type in TypeScript?

Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
2110

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
2111

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
2112

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
2113

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
2114

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
2115

How do you do visual regression testing?

Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
2116

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
2117

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
2118

What is the difference between click and dispatchEvent?

Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
2119

How do you wait for a network response in Playwright?

Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
2120

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
2121

Explain the event loop.

Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
2122

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
2123

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
2124

How do you reuse login state across tests?

Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
2125

What are interfaces and types in TypeScript?

Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
2126

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
2127

What are fixtures in Playwright?

Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
2128

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
2129

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
2130

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
2131

How do you perform drag and drop and hover?

Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
2132

How do you integrate Playwright with Allure or other reports?

Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
2133

What are higher-order functions?

Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
2134

How do you share cookies between API login and UI?

Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
2135

How do you run tests in Docker?

Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
2136

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
2137

How do you run Playwright in GitHub Actions?

Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
2138

How do you handle token refresh in long API test runs?

Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
2139

How do you mock third-party APIs in UI tests?

Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
2140

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
2141

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
2142

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
2143

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
2144

How do you mock network requests?

Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
2145

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
2146

How do you handle file uploads and downloads?

Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
2147

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
2148

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
2149

How do you debug a Playwright test?

Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
2150

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
2151

What reporters does Playwright provide?

Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
2152

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
2153

How do you combine API and UI tests?

Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
2154

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
2155

What are closures?

Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
2156

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
2157

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
2158

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
2159

What are global setup and teardown?

Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
2160

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
2161

How do you set test timeouts?

Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
2162

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
2163

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
2164

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
2165

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
2166

How do you test geolocation, permissions and time zones?

Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
2167

What are soft assertions?

Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
2168

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
2169

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
2170

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
2171

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
2172

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
2173

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
2174

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
2175

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
2176

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
2177

How do you mock network requests?

Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
2178

What happens if you forget an await?

Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
2179

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
2180

Write an API test with the request fixture.

Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
2181

What are web-first assertions?

Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
2182

What are soft assertions?

Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
2183

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
2184

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
2185

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
2186

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
2187

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
2188

What is the difference between null and undefined?

Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
2189

Promise.all vs Promise.allSettled vs Promise.race?

Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
2190

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
2191

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
2192

What are global setup and teardown?

Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
2193

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
2194

How do you structure environment-specific configs in Playwright?

Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
2195

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
2196

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
2197

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
2198

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
2199

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
2200

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
2201

How do you send authentication headers?

Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
2202

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
2203

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
2204

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
2205

What are interfaces and types in TypeScript?

Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
2206

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
2207

What are higher-order functions?

Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
2208

How do you run Playwright in GitHub Actions?

Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
2209

What are closures?

Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
2210

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
2211

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
2212

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
2213

What reporters does Playwright provide?

Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
2214

How do you send a POST request with a JSON body?

Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
2215

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
2216

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
2217

What is the difference between click and dispatchEvent?

Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
2218

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
2219

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
2220

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
2221

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
2222

How do you handle file uploads and downloads?

Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
2223

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
2224

How do you share cookies between API login and UI?

Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
2225

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
2226

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
2227

What are interfaces and types in TypeScript?

Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
2228

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
2229

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
2230

interface vs type in TypeScript?

Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
2231

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
2232

How do you run tests on mobile viewports?

Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
2233

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
2234

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
2235

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
2236

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
2237

How do you mock network requests?

Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
2238

Explain the event loop.

Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
2239

What are generics in TypeScript?

Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
2240

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
2241

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
2242

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
2243

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
2244

What reporters does Playwright provide?

Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
2245

How do you do visual regression testing?

Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
2246

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
2247

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
2248

How do you wait for a network response in Playwright?

Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
2249

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
2250

How do you test geolocation, permissions and time zones?

Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
2251

What is the difference between null and undefined?

Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
2252

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
2253

What does the optional chaining operator do?

Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
2254

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
2255

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
2256

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
2257

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
2258

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
2259

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
2260

What is APIRequestContext?

Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
2261

How do you handle token refresh in long API test runs?

Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
2262

How do you send a POST request with a JSON body?

Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
2263

What are fixtures in Playwright?

Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
2264

How do you handle date pickers and custom dropdowns?

Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
2265

How do you combine API and UI tests?

Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
2266

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
2267

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
2268

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
2269

How do you test a file download?

Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
2270

What happens if you forget an await?

Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
2271

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
2272

How do you mock third-party APIs in UI tests?

Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
2273

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
2274

How do you integrate Playwright with Allure or other reports?

Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
2275

What are closures?

Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
2276

How do you set test timeouts?

Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
2277

Write an API test with the request fixture.

Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
2278

How do you run tests in Docker?

Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
2279

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
2280

What are higher-order functions?

Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
2281

How do you run Playwright in GitHub Actions?

Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
2282

How do you run tests in parallel and control workers?

Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
2283

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
2284

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
2285

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
2286

How do you debug a Playwright test?

Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
2287

How do you mock an API response?

StripeMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
2288

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
2289

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
2290

How do you handle date pickers and custom dropdowns?

StripeMedium
Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
2291

What is the difference between beforeEach and fixtures?

StripeMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
2292

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
2293

How do you handle file uploads and downloads?

StripeMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
2294

How do you send a POST request with a JSON body?

StripeMedium
Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
2295

How do you handle GraphQL APIs in Playwright?

StripeMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
2296

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
2297

How do you debug a Playwright test?

StripeMedium
Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
2298

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
2299

How do you test geolocation, permissions and time zones?

StripeMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
2300

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
2301

How do you run tests in Docker?

StripeMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
2302

What are global setup and teardown?

StripeMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
2303

How do you validate an API response in Playwright?

StripeMedium
Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
2304

How do you send authentication headers?

StripeMedium
Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
2305

How do you reuse login state across tests?

StripeMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
2306

How do you manage test data and environments?

StripeMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
2307

How do you structure environment-specific configs in Playwright?

StripeMedium
Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
2308

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
2309

What are soft assertions?

StripeMedium
Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
2310

How do you set test timeouts?

StripeMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
2311

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
2312

Promise.all vs Promise.allSettled vs Promise.race?

StripeMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
2313

How do you integrate Playwright with Allure or other reports?

StripeMedium
Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
2314

How do you measure API response time?

StripeMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
2315

How do you handle rate limits or slow APIs in tests?

StripeMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
2316

How do retries work?

StripeMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
2317

What is destructuring and the spread operator?

StripeMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
2318

How do you mock third-party APIs in UI tests?

StripeMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
2319

How do you perform drag and drop and hover?

StripeMedium
Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
2320

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
2321

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
2322

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
2323

How do you wait for a network response in Playwright?

StripeMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
2324

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
2325

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
2326

How does Playwright compare with Selenium and Cypress?

StripeMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
2327

What are fixtures and how do you create a custom one?

StripeMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
2328

interface vs type in TypeScript?

StripeMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
2329

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
2330

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
2331

What are generics in TypeScript?

StripeMedium
Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
2332

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
2333

How do you handle token refresh in long API test runs?

StripeMedium
Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
2334

What are higher-order functions?

StripeMedium
Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
2335

What is the difference between waitForSelector and expect with locator?

StripeMedium
Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
2336

What is the difference between synchronous and asynchronous code?

StripeMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
2337

How do you tag and filter tests?

StripeMedium
Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
2338

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
2339

Why choose Playwright over Selenium?

StripeMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
2340

What are closures?

StripeMedium
Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
2341

How do you take screenshots and videos?

StripeMedium
Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
2342

What are interfaces and types in TypeScript?

StripeMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
2343

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
2344

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
2345

How do you handle iframes in Playwright?

PayPalMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
2346

How do you manage test data and environments?

PayPalMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
2347

How do you structure environment-specific configs in Playwright?

PayPalMedium
Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
2348

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
2349

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
2350

How do you tag and filter tests?

PayPalMedium
Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
2351

What is the difference between beforeEach and fixtures?

PayPalMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
2352

How do you perform drag and drop and hover?

PayPalMedium
Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
2353

What are closures?

PayPalMedium
Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
2354

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
2355

How do you handle file uploads and downloads?

PayPalMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
2356

How do you share cookies between API login and UI?

PayPalMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
2357

What are higher-order functions?

PayPalMedium
Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
2358

What are fixtures in Playwright?

PayPalMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
2359

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
2360

How do you reuse login state across tests?

PayPalMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
2361

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
2362

Why choose Playwright over Selenium?

PayPalMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
2363

What are global setup and teardown?

PayPalMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
2364

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
2365

How does visual testing work in Playwright?

PayPalMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
2366

What is the difference between waitForSelector and expect with locator?

PayPalMedium
Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
2367

What is hoisting?

PayPalMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
2368

How do you test file downloads and verify their content?

PayPalMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
2369

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
2370

How do you run tests in parallel and control workers?

PayPalMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
2371

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
2372

How do you test API error scenarios?

PayPalMedium
Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
2373

How do you measure API response time?

PayPalMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
2374

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
2375

What is destructuring and the spread operator?

PayPalMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
2376

How do you integrate Playwright with Allure or other reports?

PayPalMedium
Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
2377

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
2378

How do you handle token refresh in long API test runs?

PayPalMedium
Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
2379

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
2380

How do you handle rate limits or slow APIs in tests?

PayPalMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
2381

How do you handle date pickers and custom dropdowns?

PayPalMedium
Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
2382

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
2383

What are interfaces and types in TypeScript?

PayPalMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
2384

What does the optional chaining operator do?

PayPalMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
2385

How do you mock third-party APIs in UI tests?

PayPalMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
2386

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
2387

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
2388

How do you send authentication headers?

Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
2389

How do you run tests on mobile viewports?

Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
2390

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
2391

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
2392

What are soft assertions?

Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
2393

Promise.all vs Promise.allSettled vs Promise.race?

Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
2394

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
2395

How do you test pagination or chained API calls?

Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
2396

How do you run tests in Docker?

Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
2397

How do you mock network requests?

Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
2398

What are web-first assertions?

Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
2399

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
2400

How do you perform drag and drop and hover?

Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
2401

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
2402

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
2403

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
2404

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
2405

How do you handle authentication to avoid logging in every test?

Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
2406

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
2407

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
2408

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
2409

How do you set test timeouts?

Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
2410

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
2411

How do you share cookies between API login and UI?

Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
2412

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
2413

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
2414

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
2415

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
2416

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
2417

How do you structure environment-specific configs in Playwright?

Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
2418

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
2419

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
2420

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
2421

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
2422

What does the optional chaining operator do?

Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
2423

What happens if you forget an await?

Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
2424

interface vs type in TypeScript?

Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
2425

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
2426

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
2427

How do you handle shadow DOM?

Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
2428

What are higher-order functions?

Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
2429

What are interfaces and types in TypeScript?

Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
2430

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
2431

How do you handle rate limits or slow APIs in tests?

Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
2432

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
2433

How do you manage test data and environments?

Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
2434

How do you write a Page Object in Playwright?

AdobeEasy
Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
2435

Locator vs ElementHandle?

AdobeEasy
Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
2436

How do you mock third-party APIs in UI tests?

AdobeMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
2437

How do you run only smoke tests?

AdobeEasy
Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
2438

How do you work with iframes?

AdobeEasy
Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
2439

How do you handle iframes in Playwright?

AdobeMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
2440

How do you manage test data and environments?

AdobeMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
2441

How do you handle date pickers and custom dropdowns?

AdobeMedium
Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
2442

What are soft assertions?

AdobeMedium
Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
2443

What are higher-order functions?

AdobeMedium
Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
2444

What does the optional chaining operator do?

AdobeMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
2445

What is APIRequestContext?

AdobeMedium
Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
2446

How do you run Playwright in GitHub Actions?

AdobeMedium
Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
2447

What are generics in TypeScript?

AdobeMedium
Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
2448

How do you handle authentication to avoid logging in every test?

AdobeMedium
Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
2449

What are fixtures in Playwright?

AdobeMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
2450

What is npm and package.json?

AdobeEasy
Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
2451

How do you run tests in Docker?

AdobeMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
2452

How do you test geolocation, permissions and time zones?

AdobeMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
2453

How do you tag and filter tests?

AdobeMedium
Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
2454

What is the difference between a type and an enum in TypeScript?

AdobeMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
2455

How do you set test timeouts?

AdobeMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
2456

What is destructuring and the spread operator?

AdobeMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
2457

How do you create test data through the API before a UI test?

AdobeHard
Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
2458

What is auto-waiting in Playwright?

AdobeEasy
Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
2459

How do you take screenshots and videos?

AdobeMedium
Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
2460

What are global setup and teardown?

AdobeMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
2461

How do you handle errors in async code?

AdobeEasy
Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
2462

What are closures?

AdobeMedium
Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
2463

What are the main data types in JavaScript?

AdobeEasy
Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
2464

How do you debug a Playwright test?

AdobeMedium
Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
2465

How do you handle multiple tabs or pop-ups?

AdobeMedium
Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
2466

How do retries work?

AdobeMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
2467

How do you test file downloads and verify their content?

AdobeMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
2468

How do you measure API response time?

AdobeMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
2469

How does visual testing work in Playwright?

AdobeMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
2470

How do you test a file download?

AdobeMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
2471

What is the difference between map, filter and reduce?

AdobeMedium
Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
2472

Design a Playwright framework for a 500-test suite.

AdobeHard
Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
2473

What is the difference between synchronous and asynchronous code?

AdobeMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
2474

How would you handle a very flaky element that appears after an animation?

AdobeHard
Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
2475

Explain the event loop.

AdobeMedium
Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
2476

How would you structure a large Playwright framework for a team?

AdobeHard
Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
2477

What happens if you forget an await?

AdobeMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
2478

What is the difference between waitForSelector and expect with locator?

AdobeMedium
Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
2479

How do you send authentication headers?

AdobeMedium
Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
2480

How do you test file upload via API?

AdobeMedium
Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
2481

How do you send a POST request with a JSON body?

AdobeMedium
Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
2482

What are fixtures and how do you create a custom one?

AdobeMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
2483

Tests are flaky in CI. How do you debug them?

AdobeHard
Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
2484

What is codegen?

AdobeMedium
Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
2485

What are arrow functions?

AdobeEasy
Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
2486

How do retries work?

FlipkartMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
2487

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
2488

How do you handle iframes in Playwright?

FlipkartMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
2489

How do you wait for a network response in Playwright?

FlipkartMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
2490

How do you integrate Playwright with Allure or other reports?

FlipkartMedium
Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
2491

How do you organise tests with page object model in Playwright?

FlipkartMedium
Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
2492

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
2493

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
2494

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
2495

How do you send authentication headers?

FlipkartMedium
Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
2496

interface vs type in TypeScript?

FlipkartMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
2497

What are interfaces and types in TypeScript?

FlipkartMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
2498

How do you handle token refresh in long API test runs?

FlipkartMedium
Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
2499

What are fixtures in Playwright?

FlipkartMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
2500

What does the optional chaining operator do?

FlipkartMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
2501

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
2502

How do you handle dialogs such as alerts?

FlipkartMedium
Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
2503

Explain the event loop.

FlipkartMedium
Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
2504

How do you send a POST request with a JSON body?

FlipkartMedium
Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
2505

How do you combine API and UI tests?

FlipkartMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
2506

How do you mock an API response?

FlipkartMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
2507

What happens if you forget an await?

FlipkartMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
2508

Which locators does Playwright recommend?

FlipkartMedium
Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
2509

How do you validate an API response in Playwright?

FlipkartMedium
Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
2510

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
2511

How do you mock network requests?

FlipkartMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
2512

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
2513

What is the difference between map, filter and reduce?

FlipkartMedium
Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
2514

What is codegen?

FlipkartMedium
Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
2515

How do you validate JSON schema?

PhonePeMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
2516

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
2517

What are projects in playwright.config?

PhonePeMedium
Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
2518

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
2519

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
2520

How do you handle date pickers and custom dropdowns?

PhonePeMedium
Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
2521

How does Playwright's trace viewer help?

PhonePeMedium
Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
2522

What is destructuring and the spread operator?

PhonePeMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
2523

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
2524

How do you mock third-party APIs in UI tests?

PhonePeMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
2525

How does visual testing work in Playwright?

PhonePeMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
2526

How do you handle rate limits or slow APIs in tests?

PhonePeMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
2527

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
2528

How do you validate an API response in Playwright?

PhonePeMedium
Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
2529

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
2530

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
2531

How do you set test timeouts?

PhonePeMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
2532

What are closures?

PhonePeMedium
Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
2533

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
2534

How do you measure API response time?

PhonePeMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
2535

How do you test a file download?

PhonePeMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
2536

What are fixtures in Playwright?

PhonePeMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
2537

What is APIRequestContext?

PhonePeMedium
Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
2538

How do you run tests in parallel and control workers?

PhonePeMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
2539

What are global setup and teardown?

PhonePeMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
2540

How do you take screenshots and videos?

PhonePeMedium
Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
2541

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
2542

Why choose Playwright over Selenium?

PhonePeMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
2543

How do you handle authentication to avoid logging in every test?

PhonePeMedium
Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
2544

How do you handle dialogs such as alerts?

PhonePeMedium
Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
2545

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
2546

How do you test geolocation, permissions and time zones?

PhonePeMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
2547

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
2548

What is the difference between null and undefined?

PhonePeMedium
Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
2549

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
2550

How do you reuse login state across tests?

PhonePeMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
2551

What are generics in TypeScript?

PhonePeMedium
Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
2552

What is the difference between page, context and browser?

PhonePeMedium
Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
2553

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
2554

How does Playwright compare with Selenium and Cypress?

PhonePeMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
2555

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
2556

How do you share cookies between API login and UI?

PhonePeMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
2557

How do you tag and filter tests?

PhonePeMedium
Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
2558

How do you send a POST request with a JSON body?

PhonePeMedium
Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
2559

How do you integrate Playwright with Allure or other reports?

PhonePeMedium
Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
2560

Explain the event loop.

PhonePeMedium
Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
2561

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
2562

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
2563

What happens if you forget an await?

PhonePeMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
2564

What is hoisting?

PhonePeMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
2565

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
2566

What is the difference between beforeEach and fixtures?

PhonePeMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
2567

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
2568

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
2569

What are web-first assertions?

PhonePeMedium
Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
2570

How do you test file upload via API?

PhonePeMedium
Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
2571

How do you test API error scenarios?

PhonePeMedium
Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
2572

What are higher-order functions?

PhonePeMedium
Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
2573

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
2574

How do you mock network requests?

PhonePeMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
2575

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
2576

How do you test pagination or chained API calls?

PhonePeMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
2577

How do you wait for a network response in Playwright?

PhonePeMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
2578

How do you run tests on mobile viewports?

PhonePeMedium
Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
2579

How do you run tests in Docker?

PhonePeMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
2580

How do you do visual regression testing?

PhonePeMedium
Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
2581

How do you debug a Playwright test?

PhonePeMedium
Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
2582

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
2583

What does the optional chaining operator do?

PhonePeMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
2584

What is the difference between click and dispatchEvent?

PhonePeMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
2585

How do you handle GraphQL APIs in Playwright?

PhonePeMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
2586

Promise.all vs Promise.allSettled vs Promise.race?

PhonePeMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
2587

How do you handle shadow DOM?

PhonePeMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
2588

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
2589

What is codegen?

MeeshoMedium
Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
2590

What are interfaces and types in TypeScript?

MeeshoMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
2591

How do you send a POST request with a JSON body?

MeeshoMedium
Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
2592

How do you handle iframes in Playwright?

MeeshoMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
2593

How do retries work?

MeeshoMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
2594

What is destructuring and the spread operator?

MeeshoMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
2595

What is the difference between null and undefined?

MeeshoMedium
Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
2596

How do you handle rate limits or slow APIs in tests?

MeeshoMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
2597

How do you wait for a network response in Playwright?

MeeshoMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
2598

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
2599

How do you tag and filter tests?

MeeshoMedium
Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
2600

What are generics in TypeScript?

MeeshoMedium
Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
2601

How do you run Playwright in GitHub Actions?

MeeshoMedium
Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
2602

How does Playwright's trace viewer help?

MeeshoMedium
Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
2603

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
2604

How do you perform drag and drop and hover?

MeeshoMedium
Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
2605

What happens if you forget an await?

MeeshoMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
2606

How do you reuse login state across tests?

MeeshoMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
2607

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
2608

What are closures?

MeeshoMedium
Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
2609

How do you handle multiple tabs or pop-ups?

MeeshoMedium
Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
2610

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
2611

How do you combine API and UI tests?

MeeshoMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
2612

What is the difference between click and dispatchEvent?

MeeshoMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
2613

How do you test pagination or chained API calls?

MeeshoMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
2614

How do you handle token refresh in long API test runs?

MeeshoMedium
Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
2615

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
2616

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
2617

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
2618

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
2619

How do you test geolocation, permissions and time zones?

MeeshoMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
2620

What is the difference between beforeEach and fixtures?

MeeshoMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
2621

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
2622

How do you validate JSON schema?

MeeshoMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
2623

How does visual testing work in Playwright?

MeeshoMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
2624

How do you handle dialogs such as alerts?

MeeshoMedium
Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
2625

How do you manage test data and environments?

MeeshoMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
2626

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
2627

How do you test accessibility with Playwright?

MeeshoMedium
Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
2628

What are fixtures and how do you create a custom one?

MeeshoMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
2629

How do you test file downloads and verify their content?

MeeshoMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
2630

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
2631

How do you mock third-party APIs in UI tests?

MeeshoMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
2632

How do you shard tests across machines?

MeeshoMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
2633

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
2634

What is the difference between page, context and browser?

MeeshoMedium
Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
2635

Promise.all vs Promise.allSettled vs Promise.race?

MeeshoMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
2636

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
2637

How do you handle date pickers and custom dropdowns?

MeeshoMedium
Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
2638

How do you mock an API response?

MeeshoMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
2639

What is the difference between a type and an enum in TypeScript?

MeeshoMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
2640

How do you use test.step and test annotations?

MeeshoMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
2641

How do you test file upload via API?

MeeshoMedium
Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
2642

What are template literals?

MeeshoMedium
Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
2643

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
2644

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
2645

How does Playwright compare with Selenium and Cypress?

MeeshoMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
2646

What are higher-order functions?

MeeshoMedium
Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
2647

How do you mock network requests?

MeeshoMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
2648

interface vs type in TypeScript?

MeeshoMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
2649

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
2650

How do you run tests in Docker?

MeeshoMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
2651

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
2652

How do you test API error scenarios?

MeeshoMedium
Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
2653

What is the difference between waitForSelector and expect with locator?

MeeshoMedium
Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
2654

What is hoisting?

MeeshoMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
2655

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
2656

How do you handle GraphQL APIs in Playwright?

MeeshoMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
2657

How do you set test timeouts?

MeeshoMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
2658

How do you handle authentication to avoid logging in every test?

MeeshoMedium
Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
2659

Why choose Playwright over Selenium?

MeeshoMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
2660

How do you send authentication headers?

MeeshoMedium
Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
2661

What are fixtures in Playwright?

MeeshoMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
2662

How do you handle file uploads and downloads?

MeeshoMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
2663

What reporters does Playwright provide?

MeeshoMedium
Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
2664

What are projects in playwright.config?

MeeshoMedium
Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
2665

How do you measure API response time?

MeeshoMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
2666

How do you handle authentication to avoid logging in every test?

CREDMedium
Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
2667

let vs const vs var?

CREDEasy
Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
2668

What are web-first assertions?

CREDMedium
Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
2669

How do you shard tests across machines?

CREDMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
2670

Explain the event loop.

CREDMedium
Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
2671

How do you measure API response time?

CREDMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
2672

How do you handle file uploads and downloads?

CREDMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
2673

interface vs type in TypeScript?

CREDMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
2674

Write a test that logs in and checks the dashboard heading.

CREDEasy
Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
2675

What are projects in playwright.config?

CREDMedium
Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
2676

How do you run a single test or file in Playwright?

CREDEasy
Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
2677

How would you structure a large Playwright framework for a team?

CREDHard
Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
2678

How do you handle token refresh in long API test runs?

CREDMedium
Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
2679

How do you reuse login state across tests?

CREDMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
2680

How do you validate JSON schema?

CREDMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
2681

How do you use test.step and test annotations?

CREDMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
2682

How do you send authentication headers?

CREDMedium
Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
2683

How do you perform drag and drop and hover?

CREDMedium
Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
2684

How do you handle GraphQL APIs in Playwright?

CREDMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
2685

How do you run tests on three browsers in parallel?

CREDEasy
Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
2686

How do you test file downloads and verify their content?

CREDMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
2687

How do you handle a new tab?

CREDEasy
Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
2688

How would you handle a very flaky element that appears after an animation?

CREDHard
Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
2689

How do you validate an API response in Playwright?

CREDMedium
Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
2690

How do you handle errors in async code?

CREDEasy
Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
2691

What is the difference between TypeScript and JavaScript?

CREDEasy
Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
2692

What are interfaces and types in TypeScript?

CREDMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
2693

What is the difference between map, filter and reduce?

CREDMedium
Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
2694

What happens if you forget an await?

CREDMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
2695

How do retries work?

CREDMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
2696

Locator vs ElementHandle?

CREDEasy
Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
2697

How do you integrate Playwright with Allure or other reports?

CREDMedium
Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
2698

How do you run tests in Docker?

CREDMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
2699

How do you make an API request in Playwright?

CREDEasy
Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
2700

What are global setup and teardown?

CREDMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
2701

What is Playwright and which browsers does it support?

CREDEasy
Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
2702

What is the difference between synchronous and asynchronous code?

CREDMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
2703

How do you handle rate limits or slow APIs in tests?

CREDMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
2704

How do you handle date pickers and custom dropdowns?

CREDMedium
Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
2705

How do you test pagination or chained API calls?

CREDMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
2706

What is the difference between click and dispatchEvent?

CREDMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
2707

What is destructuring and the spread operator?

CREDMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
2708

What are generics in TypeScript?

CREDMedium
Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
2709

How do you do visual regression testing?

CREDMedium
Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
2710

What are fixtures in Playwright?

CREDMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
2711

How do you structure environment-specific configs in Playwright?

CREDMedium
Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
2712

Which locators does Playwright recommend?

CREDMedium
Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
2713

What is the difference between API testing and UI testing?

CREDEasy
Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
2714

What is the difference between beforeEach and fixtures?

CREDMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
2715

How do you mock third-party APIs in UI tests?

CREDMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
2716

How do you handle iframes in Playwright?

CREDMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
2717

What is the difference between a type and an enum in TypeScript?

CREDMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
2718

What are soft assertions?

CREDMedium
Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
2719

What is the difference between waitForSelector and expect with locator?

CREDMedium
Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
2720

What does the optional chaining operator do?

CREDMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
2721

What are arrow functions?

CREDEasy
Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
2722

How do you write a Page Object in Playwright?

CREDEasy
Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
2723

How do you wait for a network response in Playwright?

CREDMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
2724

How do you handle multiple tabs or pop-ups?

CREDMedium
Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
2725

How do you share cookies between API login and UI?

CREDMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
2726

How does Playwright compare with Selenium and Cypress?

CREDMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
2727

How do you mock an API response?

CREDMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
2728

How do you run Playwright in GitHub Actions?

CREDMedium
Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
2729

How does visual testing work in Playwright?

CREDMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
2730

What are the main data types in JavaScript?

CREDEasy
Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
2731

What is npm and package.json?

CREDEasy
Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
2732

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
2733

How do you handle iframes in Playwright?

RazorpayMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
2734

How do you manage test data and environments?

RazorpayMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
2735

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
2736

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
2737

Explain the event loop.

RazorpayMedium
Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
2738

How do you shard tests across machines?

RazorpayMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
2739

How do you handle shadow DOM?

RazorpayMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
2740

How do you handle file uploads and downloads?

RazorpayMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
2741

What are higher-order functions?

RazorpayMedium
Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
2742

How do you run tests in parallel and control workers?

RazorpayMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
2743

How do you mock network requests?

RazorpayMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
2744

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
2745

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
2746

What is hoisting?

RazorpayMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
2747

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
2748

What are fixtures and how do you create a custom one?

RazorpayMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
2749

What happens if you forget an await?

RazorpayMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
2750

How do you run Playwright in GitHub Actions?

RazorpayMedium
Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
2751

What are soft assertions?

RazorpayMedium
Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
2752

How do you measure API response time?

RazorpayMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
2753

How do you integrate Playwright with Allure or other reports?

RazorpayMedium
Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
2754

How do you validate JSON schema?

RazorpayMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
2755

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
2756

How do you handle multiple tabs or pop-ups?

RazorpayMedium
Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
2757

What is the difference between map, filter and reduce?

RazorpayMedium
Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
2758

Write an API test with the request fixture.

RazorpayMedium
Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
2759

What reporters does Playwright provide?

RazorpayMedium
Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
2760

What is the difference between synchronous and asynchronous code?

RazorpayMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
2761

What is the difference between beforeEach and fixtures?

RazorpayMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
2762

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
2763

How do you share cookies between API login and UI?

RazorpayMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
2764

How do you mock an API response?

RazorpayMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
2765

How do you take screenshots and videos?

RazorpayMedium
Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
2766

What is destructuring and the spread operator?

RazorpayMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
2767

What is the difference between click and dispatchEvent?

RazorpayMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
2768

How do retries work?

RazorpayMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
2769

How do you tag and filter tests?

RazorpayMedium
Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
2770

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
2771

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
2772

How do you reuse login state across tests?

RazorpayMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
2773

What are global setup and teardown?

RazorpayMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
2774

interface vs type in TypeScript?

RazorpayMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
2775

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
2776

What is the difference between page, context and browser?

RazorpayMedium
Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
2777

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
2778

How do you test file downloads and verify their content?

RazorpayMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
2779

How do you test accessibility with Playwright?

RazorpayMedium
Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
2780

How do you set test timeouts?

RazorpayMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
2781

What is APIRequestContext?

RazorpayMedium
Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
2782

What is the difference between null and undefined?

RazorpayMedium
Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
2783

How do you handle authentication to avoid logging in every test?

RazorpayMedium
Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
2784

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
2785

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
2786

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
2787

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
2788

How do you send a POST request with a JSON body?

RazorpayMedium
Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
2789

How do you use test.step and test annotations?

RazorpayMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
2790

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
2791

How do you test a file download?

RazorpayMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
2792

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
2793

What are generics in TypeScript?

RazorpayMedium
Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
2794

How do you validate an API response in Playwright?

RazorpayMedium
Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
2795

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
2796

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
2797

How do you combine API and UI tests?

RazorpayMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
2798

How do you run tests in Docker?

RazorpayMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
2799

How do you structure environment-specific configs in Playwright?

RazorpayMedium
Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
2800

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
2801

How do you test file upload via API?

RazorpayMedium
Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
2802

How does Playwright's trace viewer help?

RazorpayMedium
Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
2803

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
2804

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
2805

How do you mock third-party APIs in UI tests?

RazorpayMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
2806

Which locators does Playwright recommend?

RazorpayMedium
Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
2807

How do you test geolocation, permissions and time zones?

RazorpayMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
2808

How does Playwright compare with Selenium and Cypress?

RazorpayMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
2809

How do you test pagination or chained API calls?

RazorpayMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
2810

How do you wait for a network response in Playwright?

RazorpayMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
2811

How do you send a POST request with a JSON body?

ZomatoMedium
Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
2812

How do you handle file uploads and downloads?

ZomatoMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
2813

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
2814

What are fixtures in Playwright?

ZomatoMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
2815

How do you wait for a network response in Playwright?

ZomatoMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
2816

How do you test pagination or chained API calls?

ZomatoMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
2817

What is the difference between beforeEach and fixtures?

ZomatoMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
2818

What is the difference between map, filter and reduce?

ZomatoMedium
Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
2819

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
2820

How do you handle dialogs such as alerts?

ZomatoMedium
Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
2821

How do you mock network requests?

ZomatoMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
2822

How do you use test.step and test annotations?

ZomatoMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
2823

How does visual testing work in Playwright?

ZomatoMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
2824

How do you handle token refresh in long API test runs?

ZomatoMedium
Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
2825

How do you shard tests across machines?

ZomatoMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
2826

Why choose Playwright over Selenium?

ZomatoMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
2827

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
2828

How do you test API error scenarios?

ZomatoMedium
Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
2829

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
2830

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
2831

How do you set test timeouts?

ZomatoMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
2832

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
2833

What is the difference between page, context and browser?

ZomatoMedium
Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
2834

interface vs type in TypeScript?

ZomatoMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
2835

How do you handle iframes in Playwright?

ZomatoMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
2836

How do you handle authentication to avoid logging in every test?

ZomatoMedium
Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
2837

Promise.all vs Promise.allSettled vs Promise.race?

ZomatoMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
2838

What reporters does Playwright provide?

ZomatoMedium
Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
2839

How do you structure environment-specific configs in Playwright?

ZomatoMedium
Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
2840

How do you run tests in parallel and control workers?

ZomatoMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
2841

Which locators does Playwright recommend?

ZomatoMedium
Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
2842

How do you reuse login state across tests?

ZomatoMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
2843

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
2844

How do you test a file download?

ZomatoMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
2845

How do you run tests on mobile viewports?

ZomatoMedium
Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
2846

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
2847

What are template literals?

ZomatoMedium
Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
2848

What are generics in TypeScript?

ZomatoMedium
Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
2849

How do you manage test data and environments?

ZomatoMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
2850

How do you handle rate limits or slow APIs in tests?

ZomatoMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
2851

How does Playwright compare with Selenium and Cypress?

ZomatoMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
2852

How do you organise tests with page object model in Playwright?

ZomatoMedium
Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
2853

What is hoisting?

SwiggyMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
2854

How do you run tests in Docker?

SwiggyMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
2855

Promise.all vs Promise.allSettled vs Promise.race?

SwiggyMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
2856

How do retries work?

SwiggyMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
2857

How do you handle shadow DOM?

SwiggyMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
2858

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
2859

How do you structure environment-specific configs in Playwright?

SwiggyMedium
Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
2860

What is APIRequestContext?

SwiggyMedium
Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
2861

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
2862

What reporters does Playwright provide?

SwiggyMedium
Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
2863

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
2864

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
2865

interface vs type in TypeScript?

SwiggyMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
2866

What are fixtures in Playwright?

SwiggyMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
2867

What is the difference between null and undefined?

SwiggyMedium
Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
2868

What does the optional chaining operator do?

SwiggyMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
2869

How do you wait for a network response in Playwright?

SwiggyMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
2870

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
2871

What are global setup and teardown?

SwiggyMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
2872

What is the difference between waitForSelector and expect with locator?

SwiggyMedium
Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
2873

How do you test geolocation, permissions and time zones?

SwiggyMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
2874

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
2875

How do you handle token refresh in long API test runs?

SwiggyMedium
Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
2876

How do you organise tests with page object model in Playwright?

SwiggyMedium
Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
2877

What is the difference between page, context and browser?

SwiggyMedium
Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
2878

How do you mock an API response?

SwiggyMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
2879

What happens if you forget an await?

SwiggyMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
2880

How do you integrate Playwright with Allure or other reports?

SwiggyMedium
Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
2881

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
2882

What is the difference between map, filter and reduce?

ZeptoMedium
Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
2883

What is the difference between click and dispatchEvent?

ZeptoMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
2884

How would you design API test coverage for a new endpoint?

ZeptoHard
Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
2885

What is hoisting?

ZeptoMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
2886

What is the difference between beforeEach and fixtures?

ZeptoMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
2887

How do you run tests in Docker?

ZeptoMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
2888

Why choose Playwright over Selenium?

ZeptoMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
2889

What are fixtures and how do you create a custom one?

ZeptoMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
2890

How do you test file downloads and verify their content?

ZeptoMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
2891

What reporters does Playwright provide?

ZeptoMedium
Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
2892

How do you send authentication headers?

ZeptoMedium
Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
2893

What are interfaces and types in TypeScript?

ZeptoMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
2894

How do you measure API response time?

ZeptoMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
2895

How do you shard tests across machines?

ZeptoMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
2896

Which locators does Playwright recommend?

ZeptoMedium
Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
2897

How do retries work?

ZeptoMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
2898

How do you use test.step and test annotations?

ZeptoMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
2899

How do you handle file uploads and downloads?

ZeptoMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
2900

Write a test that logs in and checks the dashboard heading.

ZeptoEasy
Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
2901

How do you validate JSON schema?

ZeptoMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
2902

How would you type the response of an API call in TypeScript?

ZeptoHard
Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
2903

What is codegen?

ZeptoMedium
Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
2904

How do you run tests on mobile viewports?

ZeptoMedium
Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
2905

How do you combine API and UI tests?

ZeptoMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
2906

How do you handle multiple tabs or pop-ups?

ZeptoMedium
Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
2907

Locator vs ElementHandle?

ZeptoEasy
Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
2908

How would you handle a very flaky element that appears after an animation?

ZeptoHard
Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
2909

What are the main data types in JavaScript?

ZeptoEasy
Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
2910

What is the difference between waitForSelector and expect with locator?

ZeptoMedium
Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
2911

How do you test geolocation, permissions and time zones?

ZeptoMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
2912

How do you handle errors in async code?

ZeptoEasy
Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
2913

What is auto-waiting in Playwright?

ZeptoEasy
Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
2914

How do you reuse login state across tests?

ZeptoMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
2915

What are projects in playwright.config?

ZeptoMedium
Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
2916

How do you handle GraphQL APIs in Playwright?

ZeptoMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
2917

How do you handle dialogs such as alerts?

ZeptoMedium
Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
2918

What are soft assertions?

ZeptoMedium
Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
2919

How do you handle shadow DOM?

ZeptoMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
2920

How do you mock third-party APIs in UI tests?

ZeptoMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
2921

What are closures?

ZeptoMedium
Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
2922

How do you handle rate limits or slow APIs in tests?

ZeptoMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
2923

How do you install and start a Playwright project?

ZeptoEasy
Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
2924

How do you handle authentication to avoid logging in every test?

ZeptoMedium
Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
2925

How do you run tests in parallel and control workers?

ZeptoMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
2926

What is async/await?

ZeptoEasy
Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
2927

How do you write a Page Object in Playwright?

ZeptoEasy
Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
2928

How do you test pagination or chained API calls?

ZeptoMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
2929

What is destructuring and the spread operator?

ZeptoMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
2930

How does visual testing work in Playwright?

ZeptoMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
2931

What are fixtures in Playwright?

ZeptoMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
2932

How do you test file upload via API?

ZeptoMedium
Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
2933

What is the difference between API testing and UI testing?

ZeptoEasy
Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
2934

How do you manage test data and environments?

ZeptoMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
2935

interface vs type in TypeScript?

ZeptoMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
2936

How do you test a file download?

ZeptoMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
2937

What is a locator in Playwright?

ZeptoEasy
Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
2938

How do you reduce the execution time of a 2000-test suite?

ZeptoHard
Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
2939

How does Playwright's trace viewer help?

ZeptoMedium
Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
2940

How do you validate an API response in Playwright?

ZeptoMedium
Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
2941

What are template literals?

ZeptoMedium
Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
2942

What does the optional chaining operator do?

ZeptoMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
2943

How do you handle a new tab?

ZeptoEasy
Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
2944

What are fixtures in Playwright?

PaytmMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
2945

What are projects in playwright.config?

PaytmMedium
Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
2946

How do you test accessibility with Playwright?

PaytmMedium
Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
2947

How do you validate an API response in Playwright?

PaytmMedium
Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
2948

How do you run Playwright in GitHub Actions?

PaytmMedium
Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
2949

How do you reduce the execution time of a 2000-test suite?

PaytmHard
Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
2950

How do you send authentication headers?

PaytmMedium
Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
2951

What is the difference between TypeScript and JavaScript?

PaytmEasy
Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
2952

How would you type the response of an API call in TypeScript?

PaytmHard
Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
2953

How do you send a POST request with a JSON body?

PaytmMedium
Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
2954

How do you create test data through the API before a UI test?

PaytmHard
Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
2955

What is the difference between a type and an enum in TypeScript?

PaytmMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
2956

Design a Playwright framework for a 500-test suite.

PaytmHard
Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
2957

How do you run tests in Docker?

PaytmMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
2958

How do you measure API response time?

PaytmMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
2959

How do you test file upload via API?

PaytmMedium
Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
2960

What are the main data types in JavaScript?

PaytmEasy
Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
2961

How do you take screenshots and videos?

PaytmMedium
Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
2962

How does Playwright's trace viewer help?

PaytmMedium
Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
2963

How do you run only smoke tests?

PaytmEasy
Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
2964

How would you handle a very flaky element that appears after an animation?

PaytmHard
Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
2965

How do you handle file uploads and downloads?

PaytmMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
2966

How do you structure environment-specific configs in Playwright?

PaytmMedium
Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
2967

How do you handle multiple tabs or pop-ups?

PaytmMedium
Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
2968

Tests are flaky in CI. How do you debug them?

PaytmHard
Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
2969

How do you test geolocation, permissions and time zones?

PaytmMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
2970

Promise.all vs Promise.allSettled vs Promise.race?

PaytmMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
2971

How do you write a Page Object in Playwright?

PaytmEasy
Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
2972

What reporters does Playwright provide?

PaytmMedium
Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
2973

How do you reuse login state across tests?

PaytmMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
2974

What are interfaces and types in TypeScript?

PaytmMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
2975

How do you perform drag and drop and hover?

Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
2976

What is the difference between click and dispatchEvent?

Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
2977

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
2978

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
2979

What is APIRequestContext?

Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
2980

How do you test geolocation, permissions and time zones?

Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
2981

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
2982

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
2983

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
2984

Promise.all vs Promise.allSettled vs Promise.race?

Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
2985

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
2986

How do you send authentication headers?

Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
2987

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
2988

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
2989

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
2990

What are fixtures in Playwright?

Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
2991

What are global setup and teardown?

Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
2992

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
2993

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
2994

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
2995

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
2996

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
2997

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
2998

How do you run tests in Docker?

Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
2999

How do you run tests in parallel and control workers?

Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
3000

How do you structure environment-specific configs in Playwright?

Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
3001

What is the difference between null and undefined?

Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
3002

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
3003

How do you manage test data and environments?

Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
3004

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
3005

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
3006

What is the difference between map, filter and reduce?

Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
3007

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
3008

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
3009

What are web-first assertions?

IntuitMedium
Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
3010

How do you validate JSON schema?

IntuitMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
3011

How do you set test timeouts?

IntuitMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
3012

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
3013

How do you test pagination or chained API calls?

IntuitMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
3014

How do you share cookies between API login and UI?

IntuitMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
3015

How do you handle rate limits or slow APIs in tests?

IntuitMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
3016

What are projects in playwright.config?

IntuitMedium
Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
3017

What are fixtures in Playwright?

IntuitMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
3018

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
3019

What are template literals?

IntuitMedium
Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
3020

How do you handle multiple tabs or pop-ups?

IntuitMedium
Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
3021

How do you measure API response time?

IntuitMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
3022

What is hoisting?

IntuitMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
3023

How does visual testing work in Playwright?

IntuitMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
3024

What does the optional chaining operator do?

IntuitMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
3025

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
3026

How do you handle token refresh in long API test runs?

IntuitMedium
Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
3027

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
3028

How do you mock an API response?

IntuitMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
3029

How do retries work?

IntuitMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
3030

How do you manage test data and environments?

IntuitMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
3031

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
3032

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
3033

How do you run tests in parallel and control workers?

IntuitMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
3034

How does Playwright's trace viewer help?

IntuitMedium
Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
3035

interface vs type in TypeScript?

IntuitMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
3036

What happens if you forget an await?

IntuitMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
3037

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
3038

How do you handle GraphQL APIs in Playwright?

IntuitMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
3039

How do you wait for a network response in Playwright?

IntuitMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
3040

What reporters does Playwright provide?

IntuitMedium
Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
3041

How do you do visual regression testing?

IntuitMedium
Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
3042

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
3043

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
3044

How do you run Playwright in GitHub Actions?

IntuitMedium
Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
3045

How do you run tests on mobile viewports?

IntuitMedium
Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
3046

How do you handle iframes in Playwright?

IntuitMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
3047

Promise.all vs Promise.allSettled vs Promise.race?

IntuitMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
3048

How do you debug a Playwright test?

WalmartMedium
Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
3049

How do you handle token refresh in long API test runs?

WalmartMedium
Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
3050

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
3051

How do you shard tests across machines?

WalmartMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
3052

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
3053

How do you handle rate limits or slow APIs in tests?

WalmartMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
3054

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
3055

How do you send authentication headers?

WalmartMedium
Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
3056

How do you mock third-party APIs in UI tests?

WalmartMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
3057

How do you set test timeouts?

WalmartMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
3058

How do you run tests on mobile viewports?

WalmartMedium
Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
3059

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
3060

How do you handle file uploads and downloads?

WalmartMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
3061

How do you send a POST request with a JSON body?

WalmartMedium
Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
3062

What are web-first assertions?

WalmartMedium
Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
3063

What happens if you forget an await?

WalmartMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
3064

How do you run Playwright in GitHub Actions?

WalmartMedium
Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
3065

What is the difference between click and dispatchEvent?

WalmartMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
3066

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
3067

How do you run tests in Docker?

WalmartMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
3068

What is destructuring and the spread operator?

WalmartMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
3069

What is APIRequestContext?

WalmartMedium
Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
3070

How do you test a file download?

WalmartMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
3071

How do you test file downloads and verify their content?

WalmartMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
3072

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
3073

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
3074

Which locators does Playwright recommend?

WalmartMedium
Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
3075

How do you handle iframes in Playwright?

WalmartMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
3076

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
3077

What are interfaces and types in TypeScript?

WalmartMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
3078

What is the difference between synchronous and asynchronous code?

WalmartMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
3079

What is the difference between a type and an enum in TypeScript?

WalmartMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
3080

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
3081

What is the difference between beforeEach and fixtures?

WalmartMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
3082

What is hoisting?

WalmartMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
3083

How do you integrate Playwright with Allure or other reports?

WalmartMedium
Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
3084

How do you do visual regression testing?

WalmartMedium
Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
3085

What are soft assertions?

WalmartMedium
Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
3086

How do you handle shadow DOM?

WalmartMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
3087

What is codegen?

WalmartMedium
Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
3088

How does Playwright's trace viewer help?

WalmartMedium
Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
3089

How do you perform drag and drop and hover?

WalmartMedium
Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
3090

What are fixtures and how do you create a custom one?

WalmartMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
3091

How do you run tests in parallel and control workers?

WalmartMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
3092

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
3093

How does Playwright compare with Selenium and Cypress?

WalmartMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
3094

How do you test file upload via API?

WalmartMedium
Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
3095

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
3096

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
3097

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
3098

Which locators does Playwright recommend?

Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
3099

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
3100

How do you run tests on mobile viewports?

Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
3101

How do you send a POST request with a JSON body?

Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
3102

How do you run tests in Docker?

Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
3103

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
3104

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
3105

What is the difference between click and dispatchEvent?

Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
3106

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
3107

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
3108

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
3109

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
3110

How do you send authentication headers?

Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
3111

How do you run Playwright in GitHub Actions?

Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
3112

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
3113

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
3114

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
3115

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
3116

How do you handle shadow DOM?

Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
3117

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
3118

How do you integrate Playwright with Allure or other reports?

Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
3119

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
3120

How do you handle date pickers and custom dropdowns?

Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
3121

Explain the event loop.

Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
3122

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
3123

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
3124

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
3125

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
3126

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
3127

What is hoisting?

Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
3128

How do you wait for a network response in Playwright?

Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
3129

What are higher-order functions?

Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
3130

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
3131

How do you run tests in parallel and control workers?

Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
3132

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
3133

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
3134

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
3135

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
3136

How do you handle token refresh in long API test runs?

Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
3137

How do you test geolocation, permissions and time zones?

Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
3138

What are web-first assertions?

Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
3139

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
3140

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
3141

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
3142

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
3143

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
3144

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
3145

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
3146

How do you set test timeouts?

Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
3147

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
3148

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
3149

How do you do visual regression testing?

Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
3150

What are global setup and teardown?

Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
3151

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
3152

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
3153

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
3154

Promise.all vs Promise.allSettled vs Promise.race?

Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
3155

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
3156

What are soft assertions?

Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
3157

What are fixtures in Playwright?

Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
3158

What does the optional chaining operator do?

Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
3159

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
3160

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
3161

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
3162

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
3163

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
3164

How do you handle authentication to avoid logging in every test?

Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
3165

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
3166

Write an API test with the request fixture.

Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
3167

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
3168

What are generics in TypeScript?

Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
3169

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
3170

How do you manage test data and environments?

Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
3171

How do you share cookies between API login and UI?

Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
3172

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
3173

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
3174

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
3175

What happens if you forget an await?

Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
3176

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
3177

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
3178

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
3179

How do you manage test data and environments?

Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
3180

Write an API test with the request fixture.

Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
3181

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
3182

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
3183

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
3184

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
3185

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
3186

What are closures?

Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
3187

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
3188

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
3189

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
3190

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
3191

What reporters does Playwright provide?

Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
3192

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
3193

What are higher-order functions?

Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
3194

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
3195

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
3196

How do you run Playwright in GitHub Actions?

Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
3197

How do you handle shadow DOM?

Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
3198

How do you debug a Playwright test?

Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
3199

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
3200

What is the difference between click and dispatchEvent?

Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
3201

How do you test pagination or chained API calls?

Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
3202

How do you mock network requests?

Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
3203

How do you wait for a network response in Playwright?

Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
3204

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
3205

What are soft assertions?

Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
3206

How do you perform drag and drop and hover?

Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
3207

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
3208

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
3209

How do you share cookies between API login and UI?

Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
3210

What is the difference between synchronous and asynchronous code?

Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
3211

What are fixtures in Playwright?

Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
3212

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
3213

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
3214

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
3215

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
3216

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
3217

How do you test a file download?

Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
3218

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
3219

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
3220

How do you handle rate limits or slow APIs in tests?

Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
3221

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
3222

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
3223

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
3224

How do you handle file uploads and downloads?

Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
3225

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
3226

How do you combine API and UI tests?

Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
3227

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
3228

interface vs type in TypeScript?

Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
3229

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
3230

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
3231

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
3232

How do you integrate Playwright with Allure or other reports?

Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
3233

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
3234

Explain the event loop.

Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
3235

Write an API test with the request fixture.

Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
3236

How do you mock third-party APIs in UI tests?

Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
3237

How do you combine API and UI tests?

Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
3238

What reporters does Playwright provide?

Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
3239

What are soft assertions?

Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
3240

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
3241

What does the optional chaining operator do?

Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
3242

How do you run tests in parallel and control workers?

Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
3243

How do you set test timeouts?

Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
3244

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
3245

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
3246

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
3247

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
3248

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
3249

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
3250

What is APIRequestContext?

Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
3251

What are global setup and teardown?

Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
3252

What are fixtures in Playwright?

Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
3253

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
3254

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
3255

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
3256

How do you test a file download?

Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
3257

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
3258

How do you handle token refresh in long API test runs?

Save to ▾
Show answer
Fetch tokens in a fixture with expiry tracking and refresh it when it is about to expire, keeping tests unaware of the details.
3259

How do you send a POST request with a JSON body?

Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
3260

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
3261

What is the difference between null and undefined?

Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
3262

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
3263

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
3264

How do you handle file uploads and downloads?

Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
3265

What are higher-order functions?

Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
3266

What are web-first assertions?

Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
3267

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
3268

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
3269

What are generics in TypeScript?

Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
3270

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
3271

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
3272

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
3273

What is the difference between map, filter and reduce?

Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
3274

What is codegen?

Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
3275

What is the difference between synchronous and asynchronous code?

Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
3276

What are interfaces and types in TypeScript?

Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
3277

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
3278

What are closures?

Save to ▾
Show answer
A function that remembers variables from its outer scope even after that scope has finished. They are used for private state and factory helpers.
3279

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
3280

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
3281

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
3282

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
3283

How do you test geolocation, permissions and time zones?

Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
3284

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
3285

How do you reuse login state across tests?

Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
3286

How do you do visual regression testing?

Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
3287

interface vs type in TypeScript?

Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
3288

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
3289

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
3290

How do you test pagination or chained API calls?

Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
3291

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
3292

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
3293

How do you handle date pickers and custom dropdowns?

Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
3294

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
3295

What happens if you forget an await?

Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
3296

How do you share cookies between API login and UI?

Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
3297

How do you handle rate limits or slow APIs in tests?

Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
3298

Promise.all vs Promise.allSettled vs Promise.race?

Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
3299

How do you structure environment-specific configs in Playwright?

Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
3300

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
3301

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
3302

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
3303

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
3304

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
3305

How do you handle shadow DOM?

Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
3306

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
3307

How do you run Playwright in GitHub Actions?

Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
3308

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
3309

How do you debug a Playwright test?

OracleMedium
Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
3310

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
3311

How do you run tests on mobile viewports?

OracleMedium
Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
3312

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
3313

What is the difference between beforeEach and fixtures?

OracleMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
3314

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
3315

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
3316

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
3317

How do you take screenshots and videos?

OracleMedium
Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
3318

Explain the event loop.

OracleMedium
Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
3319

How do you organise tests with page object model in Playwright?

OracleMedium
Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
3320

Promise.all vs Promise.allSettled vs Promise.race?

OracleMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
3321

How do you handle dialogs such as alerts?

OracleMedium
Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
3322

How do you integrate Playwright with Allure or other reports?

OracleMedium
Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
3323

Locator vs ElementHandle?

Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
3324

Why choose Playwright over Selenium?

OracleMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
3325

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
3326

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
3327

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
3328

How does Playwright compare with Selenium and Cypress?

OracleMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
3329

How do you tag and filter tests?

OracleMedium
Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
3330

What are template literals?

OracleMedium
Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
3331

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
3332

What is the difference between null and undefined?

OracleMedium
Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
3333

interface vs type in TypeScript?

OracleMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
3334

How do you handle GraphQL APIs in Playwright?

OracleMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
3335

What is destructuring and the spread operator?

OracleMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
3336

What are projects in playwright.config?

OracleMedium
Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
3337

What is hoisting?

OracleMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
3338

How do you make an API request in Playwright?

Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
3339

How do you run tests in parallel and control workers?

OracleMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
3340

How do you shard tests across machines?

OracleMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
3341

What is the difference between waitForSelector and expect with locator?

OracleMedium
Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
3342

What are interfaces and types in TypeScript?

OracleMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
3343

What is the difference between a type and an enum in TypeScript?

OracleMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
3344

How do you do visual regression testing?

OracleMedium
Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
3345

What is the difference between page, context and browser?

OracleMedium
Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
3346

Which locators does Playwright recommend?

OracleMedium
Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
3347

What is the difference between map, filter and reduce?

OracleMedium
Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
3348

How do you mock third-party APIs in UI tests?

OracleMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
3349

How do you mock network requests?

OracleMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
3350

How do you handle shadow DOM?

OracleMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
3351

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
3352

How do you validate JSON schema?

OracleMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
3353

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
3354

How does Playwright's trace viewer help?

OracleMedium
Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
3355

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
3356

What are web-first assertions?

OracleMedium
Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
3357

How do you set test timeouts?

OracleMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
3358

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
3359

How do you combine API and UI tests?

OracleMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
3360

How does visual testing work in Playwright?

OracleMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
3361

What is the difference between synchronous and asynchronous code?

OracleMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
3362

How do you send authentication headers?

OracleMedium
Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
3363

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
3364

How do you test pagination or chained API calls?

OracleMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
3365

What are higher-order functions?

OracleMedium
Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
3366

How do you reuse login state across tests?

OracleMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
3367

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
3368

How do you test API error scenarios?

OracleMedium
Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
3369

What happens if you forget an await?

OracleMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
3370

What is the difference between click and dispatchEvent?

OracleMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
3371

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
3372

What are fixtures and how do you create a custom one?

OracleMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
3373

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
3374

How do you measure API response time?

OracleMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
3375

How do you test file downloads and verify their content?

OracleMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
3376

Tests are flaky in CI. How do you debug them?

CiscoHard
Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
3377

How do you write a Page Object in Playwright?

CiscoEasy
Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
3378

Why choose Playwright over Selenium?

CiscoMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
3379

What are arrow functions?

CiscoEasy
Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
3380

What is APIRequestContext?

CiscoMedium
Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
3381

How do you reduce the execution time of a 2000-test suite?

CiscoHard
Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
3382

How does visual testing work in Playwright?

CiscoMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
3383

How do you combine API and UI tests?

CiscoMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
3384

What are projects in playwright.config?

CiscoMedium
Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
3385

interface vs type in TypeScript?

CiscoMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
3386

What reporters does Playwright provide?

CiscoMedium
Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
3387

How do you share cookies between API login and UI?

CiscoMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
3388

How do you run tests on three browsers in parallel?

CiscoEasy
Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
3389

How do you handle file uploads and downloads?

CiscoMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
3390

How do you run tests in Docker?

CiscoMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
3391

How do you wait for a network response in Playwright?

CiscoMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
3392

Explain the event loop.

CiscoMedium
Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
3393

What does the optional chaining operator do?

CiscoMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
3394

How do you reuse login state across tests?

CiscoMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
3395

How do you handle GraphQL APIs in Playwright?

CiscoMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
3396

What is hoisting?

CiscoMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
3397

How do you make an API request in Playwright?

CiscoEasy
Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
3398

What are interfaces and types in TypeScript?

CiscoMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
3399

How do you handle rate limits or slow APIs in tests?

CiscoMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
3400

How do you structure environment-specific configs in Playwright?

CiscoMedium
Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
3401

How do you organise tests with page object model in Playwright?

CiscoMedium
Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
3402

How do you handle iframes in Playwright?

CiscoMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
3403

How do you handle date pickers and custom dropdowns?

CiscoMedium
Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
3404

What are higher-order functions?

CiscoMedium
Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
3405

How do you handle multiple tabs or pop-ups?

CiscoMedium
Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
3406

What is npm and package.json?

CiscoEasy
Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
3407

How do you measure API response time?

CiscoMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
3408

How do you validate an API response in Playwright?

CiscoMedium
Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
3409

What is the difference between page, context and browser?

CiscoMedium
Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
3410

How do you test a file download?

CiscoMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
3411

How do you run only smoke tests?

CiscoEasy
Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
3412

What is the difference between TypeScript and JavaScript?

CiscoEasy
Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
3413

How do you handle a new tab?

CiscoEasy
Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
3414

What are fixtures and how do you create a custom one?

CiscoMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
3415

What are web-first assertions?

CiscoMedium
Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
3416

How do you mock an API response?

CiscoMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
3417

How would you design API test coverage for a new endpoint?

CiscoHard
Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
3418

How do you shard tests across machines?

CiscoMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
3419

How do you test file downloads and verify their content?

CiscoMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
3420

Design a Playwright framework for a 500-test suite.

CiscoHard
Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
3421

What happens if you forget an await?

CiscoMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
3422

How would you structure a large Playwright framework for a team?

CiscoHard
Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
3423

How do you work with iframes?

CiscoEasy
Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
3424

How do you run tests in parallel and control workers?

CiscoMedium
Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
3425

How do you integrate Playwright with Allure or other reports?

CiscoMedium
Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
3426

What are the main data types in JavaScript?

CiscoEasy
Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
3427

How do you do visual regression testing?

CiscoMedium
Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
3428

What is the difference between beforeEach and fixtures?

CiscoMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
3429

Which locators does Playwright recommend?

CiscoMedium
Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
3430

How do you run Playwright in GitHub Actions?

CiscoMedium
Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
3431

How do you install and start a Playwright project?

CiscoEasy
Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
3432

let vs const vs var?

CiscoEasy
Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
3433

What are template literals?

CiscoMedium
Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
3434

How do you perform drag and drop and hover?

CiscoMedium
Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
3435

How does Playwright's trace viewer help?

CiscoMedium
Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
3436

How would you handle a very flaky element that appears after an animation?

CiscoHard
Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
3437

What is auto-waiting in Playwright?

CiscoEasy
Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
3438

Locator vs ElementHandle?

CiscoEasy
Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
3439

How do you wait for a network response in Playwright?

VisaMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
3440

What is the difference between click and dispatchEvent?

VisaMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
3441

How would you structure a large Playwright framework for a team?

VisaHard
Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
3442

What are fixtures in Playwright?

VisaMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
3443

How do you write a Page Object in Playwright?

VisaEasy
Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
3444

How do you test accessibility with Playwright?

VisaMedium
Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
3445

How do you create test data through the API before a UI test?

VisaHard
Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
3446

What does the optional chaining operator do?

VisaMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
3447

What are web-first assertions?

VisaMedium
Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
3448

What is npm and package.json?

VisaEasy
Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
3449

How would you handle a very flaky element that appears after an animation?

VisaHard
Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
3450

How do you mock third-party APIs in UI tests?

VisaMedium
Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
3451

What is the difference between waitForSelector and expect with locator?

VisaMedium
Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
3452

How would you type the response of an API call in TypeScript?

VisaHard
Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
3453

What happens if you forget an await?

VisaMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
3454

What is async/await?

VisaEasy
Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
3455

How do you handle errors in async code?

VisaEasy
Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
3456

How do you run tests in Docker?

VisaMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
3457

How do you use test.step and test annotations?

VisaMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
3458

How do you test geolocation, permissions and time zones?

VisaMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
3459

How do you debug a Playwright test?

VisaMedium
Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
3460

How does visual testing work in Playwright?

VisaMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
3461

What are fixtures and how do you create a custom one?

VisaMedium
Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
3462

What is the difference between map, filter and reduce?

VisaMedium
Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
3463

Write an API test with the request fixture.

VisaMedium
Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
3464

How do you structure environment-specific configs in Playwright?

VisaMedium
Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
3465

How do you run tests on mobile viewports?

VisaMedium
Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
3466

How do you validate JSON schema?

VisaMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
3467

What is codegen?

VisaMedium
Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
3468

Which locators does Playwright recommend?

VisaMedium
Save to ▾
Show answer
User-facing ones: getByRole, getByText, getByLabel, getByPlaceholder and getByTestId, which are more resilient than CSS or XPath.
3469

How do you measure API response time?

VisaMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
3470

What are the main data types in JavaScript?

VisaEasy
Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
3471

How do you test API error scenarios?

VisaMedium
Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
3472

How do you make an API request in Playwright?

VisaEasy
Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
3473

How do you handle GraphQL APIs in Playwright?

VisaMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
3474

How do you integrate Playwright with Allure or other reports?

VisaMedium
Save to ▾
Show answer
Install the allure-playwright reporter, add it in the config reporters array and generate the report from the allure-results folder in CI.
3475

Design a Playwright framework for a 500-test suite.

VisaHard
Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
3476

How does Playwright compare with Selenium and Cypress?

VisaMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
3477

What is the difference between synchronous and asynchronous code?

VisaMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
3478

What are projects in playwright.config?

VisaMedium
Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
3479

How do you set test timeouts?

VisaMedium
Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
3480

Write a test that logs in and checks the dashboard heading.

VisaEasy
Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
3481

Locator vs ElementHandle?

VisaEasy
Save to ▾
Show answer
A Locator is lazy, re-resolved on every action and auto-waits (recommended). An ElementHandle points to one DOM node and can go stale.
3482

What is auto-waiting in Playwright?

VisaEasy
Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
3483

What is the difference between a type and an enum in TypeScript?

VisaMedium
Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
3484

What reporters does Playwright provide?

VisaMedium
Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
3485

How do you handle iframes in Playwright?

VisaMedium
Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
3486

How do you reuse login state across tests?

VisaMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
3487

How do you perform drag and drop and hover?

VisaMedium
Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
3488

What is destructuring and the spread operator?

VisaMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
3489

Why choose Playwright over Selenium?

VisaMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
3490

How do you tag and filter tests?

VisaMedium
Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
3491

How do you manage test data and environments?

VisaMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
3492

Promise.all vs Promise.allSettled vs Promise.race?

VisaMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
3493

How do you test file downloads and verify their content?

VisaMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
3494

How do you handle multiple tabs or pop-ups?

VisaMedium
Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
3495

How do you work with iframes?

VisaEasy
Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
3496

What are arrow functions?

VisaEasy
Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
3497

What is Playwright and which browsers does it support?

VisaEasy
Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
3498

How do you handle rate limits or slow APIs in tests?

Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
3499

How do you reduce the execution time of a 2000-test suite?

Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
3500

How do you validate JSON schema?

Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
3501

How do you manage test data and environments?

Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
3502

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
3503

What is APIRequestContext?

Save to ▾
Show answer
The object behind the request fixture that holds base URL, headers and cookies, and can share cookies with a browser context.
3504

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
3505

How do you take screenshots and videos?

Save to ▾
Show answer
page.screenshot() for captures and config options use: { screenshot: 'only-on-failure', video: 'retain-on-failure' } for automatic evidence.
3506

What is the difference between synchronous and asynchronous code?

Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
3507

How do you mock third-party APIs in UI tests?

Save to ▾
Show answer
Use page.route to intercept the call and fulfil it with fixed JSON so tests do not depend on external systems.
3508

What are global setup and teardown?

Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
3509

How do you share cookies between API login and UI?

Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
3510

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
3511

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
3512

What are higher-order functions?

Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
3513

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
3514

How do you do visual regression testing?

Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
3515

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
3516

What is the difference between click and dispatchEvent?

Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
3517

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
3518

What reporters does Playwright provide?

Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
3519

How do you test file downloads and verify their content?

Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
3520

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
3521

How do you test accessibility with Playwright?

Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
3522

How do you handle shadow DOM?

Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
3523

How do you debug a Playwright test?

Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
3524

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
3525

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
3526

How would you structure a large Playwright framework for a team?

Save to ▾
Show answer
Separate tests, page objects, fixtures, utilities, test data and config; use tags, projects, shared auth setup, linting, code review and a CI pipeline with sharding and reports.
3527

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
3528

How do you structure environment-specific configs in Playwright?

Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
3529

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
3530

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
3531

How do you wait for a network response in Playwright?

Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
3532

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
3533

Write an API test with the request fixture.

Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
3534

How do you shard tests across machines?

Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
3535

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
3536

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
3537

How do you validate an API response in Playwright?

Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
3538

interface vs type in TypeScript?

Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
3539

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
3540

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
3541

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
3542

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
3543

What is destructuring and the spread operator?

Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
3544

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
3545

let vs const vs var?

Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
3546

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
3547

What are generics in TypeScript?

Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
3548

What are web-first assertions?

Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
3549

How do you perform drag and drop and hover?

Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
3550

What is the difference between null and undefined?

Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
3551

How do you test geolocation, permissions and time zones?

Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
3552

How do you reuse login state across tests?

Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
3553

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
3554

What are interfaces and types in TypeScript?

Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
3555

What does the optional chaining operator do?

Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
3556

What is the difference between page, context and browser?

Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
3557

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
3558

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
3559

How do you send a POST request with a JSON body?

Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
3560

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
3561

How do you combine API and UI tests?

Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
3562

How do you send authentication headers?

Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
3563

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
3564

How do you run tests in parallel and control workers?

Save to ▾
Show answer
Files run in parallel by default; set workers in the config and use test.describe.configure({ mode: 'parallel' }) for tests inside a file.
3565

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
3566

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
3567

Explain the event loop.

Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
3568

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
3569

How do you perform drag and drop and hover?

BarclaysMedium
Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
3570

How do you mock network requests?

BarclaysMedium
Save to ▾
Show answer
page.route('**/api/items', route => route.fulfill({ json: [...] })) intercepts and replies with test data; route.abort() simulates failures.
3571

What happens if you forget an await?

BarclaysMedium
Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
3572

What is the difference between API testing and UI testing?

Save to ▾
Show answer
API testing checks services directly and is fast and stable; UI testing checks the full user experience in the browser and is slower.
3573

Write an API test with the request fixture.

BarclaysMedium
Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
3574

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
3575

What reporters does Playwright provide?

BarclaysMedium
Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
3576

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
3577

How do you test geolocation, permissions and time zones?

BarclaysMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
3578

What does the optional chaining operator do?

BarclaysMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
3579

What is hoisting?

BarclaysMedium
Save to ▾
Show answer
Declarations of var and functions are moved to the top of their scope at compile time; let and const are hoisted but stay in the temporal dead zone until declared.
3580

What is the difference between waitForSelector and expect with locator?

BarclaysMedium
Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
3581

How do you validate JSON schema?

BarclaysMedium
Save to ▾
Show answer
Use a library such as zod or ajv to define the expected schema and parse the response to fail on missing or wrongly typed fields.
3582

What are higher-order functions?

BarclaysMedium
Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
3583

How do you do visual regression testing?

BarclaysMedium
Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
3584

How do you test file downloads and verify their content?

BarclaysMedium
Save to ▾
Show answer
Capture the download event, save it with download.saveAs, then read the file in Node and assert on name, size or content.
3585

What are soft assertions?

BarclaysMedium
Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
3586

What is the difference between beforeEach and fixtures?

BarclaysMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
3587

How do you wait for a network response in Playwright?

BarclaysMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
3588

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
3589

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
3590

What is the difference between page, context and browser?

BarclaysMedium
Save to ▾
Show answer
A browser is the engine instance; a context is an isolated session (cookies, storage); a page is a tab inside a context.
3591

How do you handle multiple tabs or pop-ups?

BarclaysMedium
Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.
3592

How do you run tests in Docker?

BarclaysMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
3593

What are global setup and teardown?

BarclaysMedium
Save to ▾
Show answer
Scripts that run once before or after the whole run, for seeding data, starting services or creating authentication state.
3594

What are generics in TypeScript?

BarclaysMedium
Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
3595

What are interfaces and types in TypeScript?

BarclaysMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
3596

How do you validate an API response in Playwright?

BarclaysMedium
Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
3597

How do you share cookies between API login and UI?

BarclaysMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
3598

Explain the event loop.

BarclaysMedium
Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
3599

How do you structure environment-specific configs in Playwright?

BarclaysMedium
Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
3600

How do you test pagination or chained API calls?

BarclaysMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
3601

What is the difference between map, filter and reduce?

BarclaysMedium
Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
3602

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
3603

What is the difference between synchronous and asynchronous code?

BarclaysMedium
Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
3604

Promise.all vs Promise.allSettled vs Promise.race?

BarclaysMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
3605

What is destructuring and the spread operator?

BarclaysMedium
Save to ▾
Show answer
Destructuring pulls values from arrays or objects into variables; spread expands an array or object into another, useful for copying and merging config.
3606

How do you manage test data and environments?

BarclaysMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
3607

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
3608

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
3609

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
3610

How do retries work?

BarclaysMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
3611

interface vs type in TypeScript?

BarclaysMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
3612

How do you run tests on mobile viewports?

BarclaysMedium
Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
3613

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
3614

What are fixtures in Playwright?

BarclaysMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
3615

How do you handle GraphQL APIs in Playwright?

BarclaysMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
3616

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
3617

How do you shard tests across machines?

BarclaysMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
3618

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
3619

Why choose Playwright over Selenium?

BarclaysMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
3620

How do you tag and filter tests?

BarclaysMedium
Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
3621

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
3622

How do you use test.step and test annotations?

BarclaysMedium
Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
3623

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
3624

What is Playwright and which browsers does it support?

Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
3625

let vs const vs var?

HSBCEasy
Save to ▾
Show answer
var is function-scoped and hoisted. let and const are block-scoped; const can't be reassigned (though an object it points to can change). Prefer const, then let.
3626

How do you mock an API response?

HSBCMedium
Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
3627

What is Playwright and which browsers does it support?

HSBCEasy
Save to ▾
Show answer
An open-source end-to-end testing framework from Microsoft that automates Chromium, Firefox and WebKit through one API, in multiple languages.
3628

How do you test API error scenarios?

HSBCMedium
Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
3629

How do you send a POST request with a JSON body?

HSBCMedium
Save to ▾
Show answer
await request.post('/api/users', { data: { name: 'Asha' } }) automatically sets JSON headers and serialises the payload.
3630

How do you test a file download?

HSBCMedium
Save to ▾
Show answer
const [download] = await Promise.all([ page.waitForEvent('download'), page.getByText('Export').click(), ]); await download.saveAs('reports/file.csv');
3631

interface vs type in TypeScript?

HSBCMedium
Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
3632

How do you reduce the execution time of a 2000-test suite?

HSBCHard
Save to ▾
Show answer
Run in parallel with sharding, reuse authentication state, set up data through APIs, avoid unnecessary waits, run smoke on every commit and the full suite nightly.
3633

How do you test pagination or chained API calls?

HSBCMedium
Save to ▾
Show answer
Read the next page link or IDs from earlier responses, loop until done and assert counts and uniqueness; pass IDs between calls in the same test.
3634

How do you handle file uploads and downloads?

HSBCMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
3635

What are fixtures in Playwright?

HSBCMedium
Save to ▾
Show answer
Reusable setup/teardown units injected into tests (page, context, request). You can extend test with custom fixtures such as loggedInPage.
3636

How do you share cookies between API login and UI?

HSBCMedium
Save to ▾
Show answer
Log in with request.post, call request.storageState(), and create a browser context using that state.
3637

How do you handle shadow DOM?

HSBCMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
3638

How do you run tests in Docker?

HSBCMedium
Save to ▾
Show answer
Use the official Playwright image which contains browsers and dependencies, mount the project and run npx playwright test for consistent CI environments.
3639

What is the difference between null and undefined?

HSBCMedium
Save to ▾
Show answer
undefined means a variable has not been assigned; null is an intentional empty value.
3640

How do you run only smoke tests?

HSBCEasy
Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
3641

Promise.all vs Promise.allSettled vs Promise.race?

HSBCMedium
Save to ▾
Show answer
all waits for every promise and rejects on the first failure; allSettled waits for all and reports each outcome; race settles with the first one to finish.
3642

How do you combine API and UI tests?

HSBCMedium
Save to ▾
Show answer
Create test data through API calls, verify it in the UI and clean up via API, which makes UI tests faster and more reliable.
3643

What is the difference between beforeEach and fixtures?

HSBCMedium
Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
3644

What are web-first assertions?

HSBCMedium
Save to ▾
Show answer
Assertions like expect(locator).toBeVisible() that retry until they pass or time out, unlike one-off checks.
3645

What is a locator in Playwright?

HSBCEasy
Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
3646

How do you structure environment-specific configs in Playwright?

HSBCMedium
Save to ▾
Show answer
Use dotenv files per environment, read them in playwright.config and set baseURL and credentials from variables, selecting with an ENV flag.
3647

How would you handle a very flaky element that appears after an animation?

HSBCHard
Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
3648

Why choose Playwright over Selenium?

HSBCMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
3649

How do you test accessibility with Playwright?

HSBCMedium
Save to ▾
Show answer
Integrate axe-core through @axe-core/playwright, run an analysis on the page and assert that there are no violations.
3650

How do you shard tests across machines?

HSBCMedium
Save to ▾
Show answer
Use npx playwright test --shard=1/4 in each CI job and merge reports afterwards to reduce total run time.
3651

How do retries work?

HSBCMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
3652

How do you handle rate limits or slow APIs in tests?

HSBCMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
3653

How do you reuse login state across tests?

HSBCMedium
Save to ▾
Show answer
Log in once in global setup, save storageState to a JSON file and set use.storageState in the config so every test starts logged in.
3654

What are soft assertions?

HSBCMedium
Save to ▾
Show answer
await expect.soft(locator).toHaveText('...') records the failure but lets the test continue, so you see every mismatch in one run.
3655

What are generics in TypeScript?

HSBCMedium
Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
3656

What is the difference between TypeScript and JavaScript?

HSBCEasy
Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
3657

How does Playwright's trace viewer help?

HSBCMedium
Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
3658

How do you validate an API response in Playwright?

HSBCMedium
Save to ▾
Show answer
Assert the status with expect(res.status()).toBe(200), parse res.json() and check fields, using schema validation for the structure.
3659

Write an API test with the request fixture.

HSBCMedium
Save to ▾
Show answer
test('get user', async ({ request }) => { const res = await request.get('/api/users/1'); expect(res.ok()).toBeTruthy(); expect((await res.json()).id).toBe(1); });
3660

How do you write a Page Object in Playwright?

HSBCEasy
Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
3661

Explain the event loop.

HSBCMedium
Save to ▾
Show answer
JavaScript runs one call stack and uses queues for async work; the event loop pushes callbacks from the microtask (promises) and task queues when the stack is empty.
3662

What is async/await?

HSBCEasy
Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
3663

How does visual testing work in Playwright?

HSBCMedium
Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
3664

How do you perform drag and drop and hover?

HSBCMedium
Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
3665

How do you manage test data and environments?

HSBCMedium
Save to ▾
Show answer
Use environment variables or .env files, a baseURL in config, API calls for setup and cleanup, and unique data per run.
3666

How do you make an API request in Playwright?

HSBCEasy
Save to ▾
Show answer
Use the request fixture: const res = await request.get('/api/users'); expect(res.ok()).toBeTruthy(); const body = await res.json();
3667

How do you handle GraphQL APIs in Playwright?

HSBCMedium
Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
3668

How do you handle date pickers and custom dropdowns?

HSBCMedium
Save to ▾
Show answer
Click to open the control, then use getByRole('option') or a text locator for the target item, instead of relying on fragile index-based selectors.
3669

What does the optional chaining operator do?

HSBCMedium
Save to ▾
Show answer
obj?.a?.b safely reads nested properties and returns undefined instead of throwing if something in the chain is missing.
3670

How do you run tests on mobile viewports?

HSBCMedium
Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
3671

What is codegen?

HSBCMedium
Save to ▾
Show answer
npx playwright codegen records user actions and generates test code with suggested locators, handy for starting tests.
3672

How do you wait for a network response in Playwright?

HCLTechMedium
Save to ▾
Show answer
Use page.waitForResponse(res => res.url().includes('/api/orders') && res.ok()) together with the action that triggers it.
3673

How do you measure API response time?

HCLTechMedium
Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
3674

Why choose Playwright over Selenium?

HCLTechMedium
Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
3675

How does Playwright compare with Selenium and Cypress?

HCLTechMedium
Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
3676

How do you tag and filter tests?

HCLTechMedium
Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
3677

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
3678

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
3679

What are interfaces and types in TypeScript?

HCLTechMedium
Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
3680

What are arrow functions?

Save to ▾
Show answer
A short function syntax that does not have its own this and arguments, taking them from the surrounding scope.
3681

How do you handle rate limits or slow APIs in tests?

HCLTechMedium
Save to ▾
Show answer
Add retries with backoff for the API step, set a suitable timeout, and use mocks for non-critical dependencies.
3682

How do you test geolocation, permissions and time zones?

HCLTechMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
3683

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
3684

How do you run tests on mobile viewports?

HCLTechMedium
Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
3685

How do you run Playwright in GitHub Actions?

HCLTechMedium
Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
3686

Tests are flaky in CI. How do you debug them?

Save to ▾
Show answer
Turn on trace: 'on-first-retry', open the trace viewer, check network and timing, replace hard waits with web-first assertions, isolate test data and check for sharding conflicts.
3687

How do you send authentication headers?

HCLTechMedium
Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
3688

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
3689

How do retries work?

HCLTechMedium
Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
3690

How do you handle authentication to avoid logging in every test?

HCLTechMedium
Save to ▾
Show answer
Log in once in a setup project, save storageState to a file and reuse it in other projects or tests.
3691

What is npm and package.json?

Save to ▾
Show answer
npm is the Node package manager. package.json lists the project's dependencies and scripts, such as the command that runs the tests.
3692

How do you create test data through the API before a UI test?

Save to ▾
Show answer
In a fixture or beforeEach, call the API (request.post) to create the user or order, use it in the UI test, then delete it in teardown. It is faster and more reliable than creating data through the UI.
3693

What reporters does Playwright provide?

HCLTechMedium
Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
3694

What is the difference between click and dispatchEvent?

HCLTechMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
3695

How do you handle file uploads and downloads?

HCLTechMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
3696

How do you test file upload via API?

HCLTechMedium
Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
3697

How do you do visual regression testing?

Save to ▾
Show answer
Use expect(page).toHaveScreenshot() to compare with stored baselines, with thresholds and masks for dynamic regions.
3698

How do you handle GraphQL APIs in Playwright?

Save to ▾
Show answer
POST the query and variables as JSON to the single endpoint and assert both data and errors fields in the response.
3699

How do you set test timeouts?

Save to ▾
Show answer
Use timeout and expect.timeout in config, test.setTimeout() for one test and test.slow() for known slower tests.
3700

How do you handle errors in async code?

Save to ▾
Show answer
Use try-catch with await, or .catch() on promises, and make sure rejected promises are never left unhandled.
3701

What is a locator in Playwright?

Save to ▾
Show answer
An object describing how to find an element, re-evaluated on every action so it always targets the current DOM.
3702

How do you write a Page Object in Playwright?

Save to ▾
Show answer
A class receives page in its constructor, stores locators as properties and exposes actions like login(user, pass). Tests call page objects, not raw locators.
3703

What is the difference between a type and an enum in TypeScript?

Save to ▾
Show answer
A type alias describes a shape or union of values; an enum creates a named set of constants that exists at runtime.
3704

What is the difference between map, filter and reduce?

Save to ▾
Show answer
map transforms each item, filter keeps items that match a condition, and reduce combines all items into a single value.
3705

How do you install and start a Playwright project?

Save to ▾
Show answer
Run npm init playwright@latest, which sets up config, example tests and browsers; execute with npx playwright test.
3706

What is the difference between synchronous and asynchronous code?

Save to ▾
Show answer
Synchronous code runs line by line and blocks; asynchronous code starts a task and continues, handling the result later with promises or await.
3707

How do you mock an API response?

Save to ▾
Show answer
await page.route('**/api/users', route => route.fulfill({ status: 200, json: [{ id: 1, name: 'Test' }] }) );
3708

How do you organise tests with page object model in Playwright?

Save to ▾
Show answer
Create a class that takes a page, defines locators as properties and exposes action methods; instantiate it in a fixture for clean tests.
3709

How would you design API test coverage for a new endpoint?

Save to ▾
Show answer
Cover happy path, validation errors, auth and permissions, boundary values, idempotency, schema, performance and data cleanup.
3710

How do you measure API response time?

Save to ▾
Show answer
Record timestamps around the request or use response timing, then assert the duration is under an agreed threshold.
3711

How do you run tests on three browsers in parallel?

Save to ▾
Show answer
Define projects for chromium, firefox and webkit in playwright.config.ts, set workers, then run: npx playwright test
3712

What are the main data types in JavaScript?

Save to ▾
Show answer
string, number, boolean, null, undefined, symbol, bigint and object (including arrays and functions).
3713

What happens if you forget an await?

Save to ▾
Show answer
The action runs without waiting, so the next step may run first — causing flaky failures or 'Target closed' errors. The @typescript-eslint/no-floating-promises rule catches it.
3714

What is the difference between waitForSelector and expect with locator?

Save to ▾
Show answer
waitForSelector is a lower-level wait; locator assertions are preferred as they retry and are more readable.
3715

Design a Playwright framework for a 500-test suite.

Save to ▾
Show answer
TypeScript + POM + custom fixtures, environment configs, API helpers for test data, tags like @smoke, sharding across CI machines, retries with traces, HTML/Allure reports, lint and review rules.
3716

How do you run only smoke tests?

Save to ▾
Show answer
Tag tests (in the title or with { tag: '@smoke' }) and run: npx playwright test --grep @smoke (use --grep-invert to exclude).
3717

How do you send authentication headers?

Save to ▾
Show answer
Set extraHTTPHeaders in the config or pass headers per request, for example Authorization: Bearer token fetched in a setup step.
3718

How do you run Playwright in GitHub Actions?

Save to ▾
Show answer
Workflow: checkout → setup-node → npm ci → npx playwright install --with-deps → npx playwright test → upload playwright-report as an artifact.
3719

How do you use test.step and test annotations?

Save to ▾
Show answer
test.step groups actions into named steps in reports; annotations such as test.skip, test.fixme and test.slow communicate intent and adjust behaviour.
3720

What is async/await?

Save to ▾
Show answer
Syntax over Promises: an async function returns a Promise and await pauses until it resolves. Every Playwright action returns a Promise, so you await each step.
3721

How do retries work?

Save to ▾
Show answer
Set retries in the config or CLI and failed tests re-run in a fresh context, with trace recorded on first retry to diagnose flakiness.
3722

How does Playwright compare with Selenium and Cypress?

Save to ▾
Show answer
Playwright supports multiple browsers, tabs, languages and has auto-waiting and tracing; Selenium has the widest ecosystem; Cypress runs in-browser with a great UI but has more limits across tabs.
3723

How do you handle iframes in Playwright?

Save to ▾
Show answer
Use page.frameLocator('#frame').getByRole(...) so actions work inside the iframe with auto-waiting.
3724

How do you debug a Playwright test?

Save to ▾
Show answer
Use --debug or the Inspector, page.pause(), UI mode, the trace viewer and headed runs with slowMo.
3725

What reporters does Playwright provide?

Save to ▾
Show answer
List, dot, line, HTML, JSON and JUnit reporters, plus integrations such as Allure, configurable per environment.
3726

How do you tag and filter tests?

Save to ▾
Show answer
Add tags in the title (@smoke) or use the tag option, and run with --grep @smoke or --grep-invert.
3727

How does visual testing work in Playwright?

Save to ▾
Show answer
await expect(page).toHaveScreenshot('home.png') compares against a baseline image; tune maxDiffPixels and mask dynamic areas like dates.
3728

How would you type the response of an API call in TypeScript?

Save to ▾
Show answer
Define an interface for the payload, cast or validate the parsed JSON to it (for example with zod), and use that type in assertions to catch shape changes.
3729

What are interfaces and types in TypeScript?

Save to ▾
Show answer
Both describe the shape of data. Interfaces are extendable and suit object contracts; type aliases can also model unions and primitives.
3730

How would you handle a very flaky element that appears after an animation?

Save to ▾
Show answer
Rely on auto-waiting plus a web-first assertion on the final state, disable animations in config for tests and avoid fixed timeouts.
3731

What are template literals?

Save to ▾
Show answer
Strings in backticks that allow embedded expressions like `Hello ${name}` and multi-line text, useful for building dynamic locators and URLs.
3732

interface vs type in TypeScript?

Save to ▾
Show answer
Both describe object shapes. Interfaces can be extended and merged; type aliases can also describe unions and primitives. Use interfaces for page or test-data shapes, types for unions.
3733

What is auto-waiting in Playwright?

Save to ▾
Show answer
Before acting, Playwright waits for the element to be attached, visible, stable, enabled and able to receive events — so manual waits are rarely needed.
3734

What are fixtures and how do you create a custom one?

Save to ▾
Show answer
Fixtures set up and tear down test dependencies. Extend with test.extend({ loggedInPage: async ({ page }, use) => { ...; await use(page); } }).
3735

How do you handle a new tab?

Save to ▾
Show answer
const [newPage] = await Promise.all([ context.waitForEvent('page'), page.getByText('Open').click(), ]); await newPage.waitForLoadState();
3736

What are projects in playwright.config?

Save to ▾
Show answer
Named configurations that run the same tests across different browsers, devices or environments.
3737

How do you run tests on mobile viewports?

Save to ▾
Show answer
Use device descriptors such as devices['iPhone 13'] in a project config to emulate viewport, user agent and touch.
3738

What are generics in TypeScript?

Save to ▾
Show answer
Placeholders for types that make reusable code type-safe, for example a helper function returning the same type of item that it receives.
3739

How do you test API error scenarios?

Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
3740

What are higher-order functions?

Save to ▾
Show answer
Functions that take other functions as arguments or return them, such as map, filter and reduce, or a helper that wraps retry logic around a test step.
3741

How do you work with iframes?

Save to ▾
Show answer
const frame = page.frameLocator('#payment-frame'); await frame.getByLabel('Card number').fill('4111 1111 1111 1111');
3742

What is the difference between beforeEach and fixtures?

Save to ▾
Show answer
beforeEach runs the same code before every test in scope; fixtures are lazy, composable and only set up what a test uses.
3743

Write a test that logs in and checks the dashboard heading.

Save to ▾
Show answer
test('login', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('a@b.com'); await page.getByLabel('Password').fill('secret'); await page.getByRole('button', { name: 'Login' }).click(); await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible(); });
3744

How do you test file upload via API?

Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
3745

What is the difference between TypeScript and JavaScript?

Save to ▾
Show answer
TypeScript adds static types on top of JavaScript and compiles to it. Types catch errors early and give better autocomplete, which helps in larger test suites.
3746

How do you handle dialogs such as alerts?

Save to ▾
Show answer
Register page.on('dialog', d => d.accept()) before the action triggers the dialog.
3747

How do you run a single test or file in Playwright?

Save to ▾
Show answer
npx playwright test tests/login.spec.ts, add -g "test title" to match a name, or use test.only while debugging.
3748

How does Playwright's trace viewer help?

Save to ▾
Show answer
It records screenshots, DOM snapshots, network calls and actions per step so you can replay a failed run and see exactly what happened.
3749

Why choose Playwright over Selenium?

Save to ▾
Show answer
Auto-waiting, a built-in test runner, Chromium/Firefox/WebKit with one API, network interception, the trace viewer and parallel runs out of the box — usually faster and less flaky.
3750

How do you handle multiple tabs or pop-ups?

Save to ▾
Show answer
Wait for the popup event with const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a')]), then interact with popup.