Skip to content

Top 50 Most Asked Playwright Testing Interview Questions

The questions that appear most often across company-wise sets — master these first.

Why start here

We count how often each question appears across the 155 company-wise Playwright Testing practice sets on this site and show the 50 most common. They are the safest questions to master first.

Solved — top 50Start practicing
3 QUESTIONS FREESign up 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

Visual tests pass on developers' laptops but fail in CI with tiny font differences. Why, and how do you fix it?

Visual & Accessibility TestingIn 33 company setsMedium
Save to ▾
Show answer
Font rendering, anti-aliasing and installed fonts differ between Windows, macOS and Linux, so the same page produces slightly different pixels. The fix is to generate and compare baselines in one fixed environment, usually the official Playwright Docker image used in CI. Developers update baselines by running that container locally or through a CI job, not from their own machines. Loosening thresholds should be the last resort.
02

How do you mock API calls made by a component in a component test?

Component TestingIn 32 company setsMedium
Save to ▾
Show answer
Newer Playwright versions provide a router fixture in component tests. You call router.route with a URL pattern and fulfil it with test data, much like page.route, and it can also use mock handlers written for Mock Service Worker. Alternatively, inject a fake data client through props or a provider in hooksConfig. Mocking keeps component tests fast and independent of any backend.
03

How do you test how the UI handles a 500 error from the orders API?

Network MockingIn 31 company setsMedium
Save to ▾
Show answer
Mock the endpoint with route.fulfill({ status: 500, json: { message: 'Server error' } }), then open the page. Assert the user sees a friendly error message and a retry button, and that no broken half-rendered table appears. Then make the retry return 200 and check the data loads. This covers a path that is hard to trigger on a real server.
04

Write a test that deletes a record and confirms it is gone.

API TestingIn 31 company setsMedium
Save to ▾
Show answer
test('delete product', async ({ request }) => { const created = await request.post('/api/products', { data: { name: 'Temp' } }); const { id } = await created.json(); const del = await request.delete(`/api/products/${id}`); expect(del.status()).toBe(204); const get = await request.get(`/api/products/${id}`); expect(get.status()).toBe(404); });
05

How do you take visual snapshots of each component state in component tests?

Component TestingIn 31 company setsMedium
Save to ▾
Show answer
Mount the component once per state, for example default, disabled, loading and error, and call await expect(component).toHaveScreenshot() for each. Since only the component is on the page, images are small, stable and fast to review. Run them in the same Docker image as CI. This often replaces many full-page visual tests that break for unrelated reasons.
06

How do you perform drag and drop and hover?

Playwright CoreIn 30 company setsMedium
Save to ▾
Show answer
locator.hover() and locator.dragTo(target) perform these actions, with auto-waiting for actionability.
07

How do you mock network requests?

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

How do you read environment variables safely in a TypeScript test project?

JavaScript and TypeScriptIn 30 company setsMedium
Save to ▾
Show answer
Load a .env file with a package like dotenv in playwright.config, then read process.env.BASE_URL. Values are string | undefined, so validate them early and throw a clear error if a required one is missing. Keep .env out of git and commit an .env.example instead. In CI, set the same names as secret variables.
09

How do you handle file uploads and downloads?

Playwright CoreIn 29 company setsMedium
Save to ▾
Show answer
setInputFiles on the input for uploads; for downloads wait on page.waitForEvent('download') and save or inspect the file.
10

A test must confirm that an error banner does not appear, but it always waits the full timeout. How do you fix it?

Locators and AssertionsIn 29 company setsMedium
Save to ▾
Show answer
Use a web-first negative assertion such as await expect(banner).toBeHidden() or not.toBeVisible(); they pass as soon as the element is absent, so they do not wait the full timeout. The real problem is timing: assert after a positive signal, such as the success message appearing, otherwise the banner may simply not have rendered yet and the check passes too early.
11

Component tests fail because imports like @/utils cannot be resolved, though the app builds fine. How do you fix it?

Component TestingIn 29 company setsMedium
Save to ▾
Show answer
The app uses a bundler alias that the component test bundle does not know. Add the same alias in ctViteConfig under resolve.alias, or reuse the project's Vite config by importing it. Also make sure tsconfig paths match, so editors and type checks agree. After that, clear the cache folder that the component bundler writes under playwright/.cache so the bundle rebuilds.
12

A test fails with 'Target page, context or browser has been closed'. What usually causes it?

Debugging and Trace ViewerIn 29 company setsMedium
Save to ▾
Show answer
Most often an action was not awaited, so the test finished and Playwright closed the page while the action was still running. Other causes are a test timeout closing the page, the code closing the page or context itself, or the browser crashing. Check the stack for the missing await, look at whether a timeout happened first, and turn on the lint rule for floating promises.
13

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

API TestingIn 28 company setsMedium
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.
14

How do you verify a page's URL and title after navigation?

Locators and AssertionsIn 28 company setsMedium
Save to ▾
Show answer
await page.getByRole('link', { name: 'Orders' }).click(); await expect(page).toHaveURL(/\/orders$/); await expect(page).toHaveTitle('My Orders | Shop'); // both retry, so no need to wait for navigation manually
15

How do you change part of a real API response?

Network MockingIn 28 company setsMedium
Save to ▾
Show answer
await page.route('**/api/profile', async route => { const response = await route.fetch(); const json = await response.json(); json.plan = 'premium'; await route.fulfill({ response, json }); }); await page.goto('/account'); await expect(page.getByText('Premium plan')).toBeVisible();
16

How do you mock network traffic using a HAR file?

Network MockingIn 28 company setsMedium
Save to ▾
Show answer
Record once with page.routeFromHAR('data/orders.har', { url: '**/api/**', update: true }) while running against a real server. Later runs replay the saved responses from the HAR instead of hitting the backend. You can edit the stored JSON to create edge cases. Re-record when the API changes, otherwise the replay drifts from reality.
17

How do you fail a test if the page logs any console error?

Debugging and Trace ViewerIn 28 company setsMedium
Save to ▾
Show answer
test('no console errors', async ({ page }) => { const errors: string[] = []; page.on('console', m => { if (m.type() === 'error') errors.push(m.text()); }); page.on('pageerror', e => errors.push(e.message)); await page.goto('/dashboard'); expect(errors).toEqual([]); });
18

CI runners have 2 CPU cores and workers is set to 8. Tests start timing out randomly. Why?

Parallel Runs, Sharding & ReportingIn 28 company setsMedium
Save to ▾
Show answer
Eight browsers compete for two cores and limited memory, so pages render slowly, actions hit timeouts and the app under test may also be overloaded. More workers than cores rarely helps. Set workers to match the runner, such as 2, and scale out with shards on more machines instead. Watch CPU and memory metrics in CI to confirm.
19

What is the difference between click and dispatchEvent?

Playwright CoreIn 27 company setsMedium
Save to ▾
Show answer
click simulates a real user click with actionability checks; dispatchEvent fires a DOM event directly without those checks.
20

How do you test API error scenarios?

API TestingIn 27 company setsMedium
Save to ▾
Show answer
Send invalid payloads or missing auth and assert 400, 401 or 404 codes and the error message bodies.
21

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

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

A third-party analytics script makes tests slow and flaky. What do you do?

Network MockingIn 27 company setsMedium
Save to ▾
Show answer
Block it in tests with context.route on its domain and route.abort, or fulfill it with an empty script. Analytics is not what you are testing, and blocking it removes delays and random network errors. If tracking events matter, write a few separate tests that capture the requests with waitForRequest and assert their parameters.
23

How do access modifiers help in page object classes?

JavaScript and TypeScriptIn 27 company setsMedium
Save to ▾
Show answer
private and protected hide internal locators and helper steps, so tests can only call meaningful public methods such as login or addToCart. This keeps tests readable and lets you change internals without breaking callers. readonly on the page field prevents it from being replaced. TypeScript enforces these at compile time only, not at runtime.
24

Write a GitHub Actions job that runs the suite in four shards.

Parallel Runs, Sharding & ReportingIn 27 company setsMedium
Save to ▾
Show answer
jobs: e2e: runs-on: ubuntu-latest strategy: fail-fast: false matrix: shard: [1, 2, 3, 4] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 - run: npm ci && npx playwright install --with-deps - run: npx playwright test --shard=${{ matrix.shard }}/4 --reporter=blob - uses: actions/upload-artifact@v4 with: name: blob-${{ matrix.shard }} path: blob-report
25

How do you run one group of tests serially while the rest of the suite runs in parallel?

Parallel Runs, Sharding & ReportingIn 27 company setsMedium
Save to ▾
Show answer
Put the group in its own project with fullyParallel: false and limit it to one worker, which recent versions allow with a workers setting on the project, or run it in a separate CI step with --project=serial --workers=1. Inside a file, test.describe.configure({ mode: 'serial' }) keeps order. Use project dependencies if the group must run after the parallel tests.
26

How do you validate an API response in Playwright?

API TestingIn 26 company setsMedium
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.
27

How do you handle shadow DOM?

Locators and AssertionsIn 26 company setsMedium
Save to ▾
Show answer
Playwright locators pierce open shadow roots by default, so getByRole and CSS locators work without special handling.
28

A locator matches three Delete buttons and the test fails with a strict mode violation. How do you fix it?

Locators and AssertionsIn 26 company setsMedium
Save to ▾
Show answer
First scope the locator to the item you mean, for example the row that contains the user's name: page.getByRole('row', { name: 'Ravi Kumar' }).getByRole('button', { name: 'Delete' }). Do not reach for first() or nth() as a quick fix, because the order can change and the test may delete the wrong record. Scoping by meaningful context is stable and readable.
29

How do you locate elements inside a specific row or card?

Locators and AssertionsIn 26 company setsMedium
Save to ▾
Show answer
Chain locators: find the container first, then search inside it. Example: page.getByRole('row', { name: 'INV-104' }).getByRole('button', { name: 'Download' }). Each step narrows the search area, so short names like Edit or Download stay unique. Chaining also documents intent clearly and avoids long CSS paths that break when markup changes.
30

How do you simulate a slow API to test a loading spinner?

Network MockingIn 26 company setsMedium
Save to ▾
Show answer
await page.route('**/api/report', async route => { await new Promise(r => setTimeout(r, 3000)); await route.continue(); }); await page.getByRole('button', { name: 'Generate' }).click(); await expect(page.getByRole('progressbar')).toBeVisible(); await expect(page.getByRole('progressbar')).toBeHidden();
31

How do you debug a test in VS Code with the Playwright extension?

Debugging and Trace ViewerIn 26 company setsMedium
Save to ▾
Show answer
Install the Playwright Test for VS Code extension. Open the Testing panel to see tests, then set a breakpoint in the test file and click Debug Test. Execution stops at the breakpoint with the browser open, so you can inspect variables. Turn on Show browser to watch runs, and use Pick locator or Record at cursor to add steps.
32

Show a config with a setup project and a browser project that reuses its login.

Framework Design and CI/CDIn 26 company setsMedium
Save to ▾
Show answer
projects: [ { name: 'setup', testMatch: /auth\.setup\.ts/ }, { name: 'chromium', use: { ...devices['Desktop Chrome'], storageState: '.auth/user.json' }, dependencies: ['setup'], }, ],
33

How do you run the same visual tests at mobile, tablet and desktop sizes?

Visual & Accessibility TestingIn 26 company setsMedium
Save to ▾
Show answer
Create one project per size in playwright.config, for example using devices['Pixel 7'], devices['iPad Mini'] and a desktop viewport, and point them at the same visual test files with testMatch or a tag. Because the project name is part of the baseline file name, each size keeps its own images automatically. This keeps the test code identical while covering responsive layouts.
34

How do you wrap a component in a theme or router provider using hooksConfig?

Component TestingIn 26 company setsMedium
Save to ▾
Show answer
// playwright/index.tsx import { beforeMount } from '@playwright/experimental-ct-react/hooks'; import { ThemeProvider } from '../src/theme'; export type HooksConfig = { theme?: 'light' | 'dark' }; beforeMount<HooksConfig>(async ({ App, hooksConfig }) => { return <ThemeProvider mode={hooksConfig?.theme ?? 'light'}><App /></ThemeProvider>; }); // in a test await mount(<Header />, { hooksConfig: { theme: 'dark' } });
35

How do you return a fake JSON response that depends on the request body?

Network MockingIn 26 company setsMedium
Save to ▾
Show answer
await page.route('**/api/quote', async (route) => { const body = route.request().postDataJSON(); const price = body.plan === 'pro' ? 999 : 299; await route.fulfill({ status: 200, json: { plan: body.plan, price }, }); });
36

How do you mock an API response?

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

How do you test geolocation, permissions and time zones?

Playwright CoreIn 25 company setsMedium
Save to ▾
Show answer
Set them in the context options (geolocation, permissions, timezoneId, locale) to simulate users from other regions.
38

How do you test file upload via API?

API TestingIn 25 company setsMedium
Save to ▾
Show answer
Use request.post with multipart: { file: { name, mimeType, buffer } } and assert the response and stored file details.
39

How do you run tests in Docker?

Framework Design and CI/CDIn 25 company setsMedium
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.
40

How do you wait for a network response in Playwright?

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

What are interfaces and types in TypeScript?

JavaScript and TypeScriptIn 25 company setsMedium
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.
42

How do you test a file download?

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

Write an API test with the request fixture.

API TestingIn 25 company setsMedium
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

How do you attach a screenshot or log to the report from inside a test?

Fixtures and HooksIn 25 company setsMedium
Save to ▾
Show answer
test('report', async ({ page }, testInfo) => { await page.goto('/reports'); await testInfo.attach('report page', { body: await page.screenshot(), contentType: 'image/png', }); await testInfo.attach('meta', { body: 'build 42', contentType: 'text/plain' }); });
45

How do you listen to all network requests on a page?

Network MockingIn 25 company setsMedium
Save to ▾
Show answer
Subscribe to events: page.on('request', r => ...), page.on('response', r => ...) and page.on('requestfailed', r => ...). You can log URLs, collect API calls or count failures. Unlike route, listeners only observe and cannot change traffic. They are handy for checks like 'no request returned a 5xx status during this flow'.
46

The app polls a status endpoint every few seconds. How do you test the change from Pending to Done?

Network MockingIn 25 company setsMedium
Save to ▾
Show answer
Mock the endpoint with a counter: return Pending for the first two calls and Done after that. Then assert the UI shows Pending and later Done using web-first assertions with a suitable timeout. You can also use page.clock to speed up the polling interval instead of waiting real seconds. This makes a slow real-world process quick and deterministic.
47

An API returns 200 but the body contains an error field. How should your test catch this?

API TestingIn 25 company setsMedium
Save to ▾
Show answer
Never trust status alone. Assert the body structure, for example that error is absent and data has the expected fields, ideally with a schema check. Report the issue, because returning 200 for errors breaks clients and monitoring. Add a helper that validates both status and body shape so every test checks it consistently.
48

Why should you dispose an APIRequestContext?

API TestingIn 25 company setsMedium
Save to ▾
Show answer
A context created with request.newContext() holds cookies, connections and stored responses in memory. Calling await context.dispose() frees them, and any later call on it fails. Without disposing, long runs can leak memory. The built-in request fixture is disposed automatically, so this matters for contexts you create in fixtures or helpers.
49

How do you validate response headers?

API TestingIn 25 company setsMedium
Save to ▾
Show answer
Use response.headers() for an object of lower-cased header names, or headersArray() for duplicates. Assert content-type contains application/json, cache-control matches the policy, and security headers such as strict-transport-security are present. Also check that sensitive headers like server version are not exposed. Header checks catch configuration bugs that body checks miss.
50

How do you test a page in dark mode or with reduced motion?

Playwright CoreIn 25 company setsMedium
Save to ▾
Show answer
Set colorScheme: 'dark' or reducedMotion: 'reduce' in the context options or test.use. You can also switch during a test with page.emulateMedia({ colorScheme: 'dark' }). Then assert the right styles or take a screenshot comparison. Reduced motion also helps stability, because many apps skip animations when that preference is set.

Frequently asked questions

How is this list made?

We count how often each question appears across the 155 company-wise Playwright Testing practice sets on this site and show the 50 most common. They are the safest questions to master first.

Is this enough to clear an interview?

It is the best starting point, not the finish line. After these, practise the company pages for your target employers and the sheets for your weaker topics.