Skip to content

Cognizant Playwright Testing Interview Questions & Answers

Curated interview practice questions with answers. These are practice scenarios, not a verified list of past interview questions.

Solved for CognizantStart 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

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
02

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.
03

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.
04

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');
05

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.
06

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' }] }) );
07

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.
08

What are projects in playwright.config?

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

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.
10

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.
11

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();
12

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.
13

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.
14

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.
15

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.
16

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.
17

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.
18

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.
19

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.
20

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.
21

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.
22

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.
23

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.
24

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.
25

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.
26

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.
27

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.
28

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.
29

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.
30

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.
31

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();
32

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.
33

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.
34

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.
35

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.
36

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.
37

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.
38

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.
39

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.
40

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.
41

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.
42

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.
43

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); });
44

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.
45

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.
46

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.
47

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.
48

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.
49

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.
50

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.
51

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.
52

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.
53

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.
54

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.
55

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.
56

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.
57

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.
58

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.
59

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).
60

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.
61

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.
62

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.
63

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.
64

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.
65

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.
66

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.
67

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.
68

What is codegen?

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

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.