QA Interview Hub · Knowledge base · Quizzes · Українська
24 Playwright questions that come up in QA interviews, with short answers. Open the topic in the knowledge base for a deeper explanation.
The main process collects the tests and distributes them between workers, and each worker is a separate Node.js process with its own browser. After a test fails, the worker is destroyed and a new one is started for the following tests, so that the broken state doesn't leak further. Because of this, beforeAll and worker fixtures may run again. That is why I don't keep shared state in module variables and don't rely on the order of tests.
Browser is the running browser process, the most expensive object, so it is created once per worker. BrowserContext is an isolated "profile" inside it: its own cookies, localStorage, cache and permissions, created in milliseconds. Page is one tab in a context. The Playwright runner gives each test a fresh context and page through the context and page fixtures, so one test never sees another test’s cookies or session, and parallel tests do not disturb each other. That gives me isolation without restarting the browser. A second user in a test is simply a second context.
I create two separate contexts with browser.newContext(), each with its own storageState, because a context is a separate session with its own cookies. Two pages of one context would share a session, and the second user would overwrite the first. Alice sends a message on her page, and on Bob's page I check that it appeared. I always close manually created contexts, ideally in a fixture, so the teardown runs even when the test fails.
I subscribe to the pageerror event, which fires on unhandled exceptions, and to console with the type error. I collect the errors in an array and after the test check that it is empty. To avoid duplicating this in every test, I move the logic into an auto fixture. I filter out console errors from third-party scripts, such as analytics, because they are noisy.
Playwright recommends locators that mirror how a user sees the page: getByRole (with name), getByLabel, getByPlaceholder, getByText, and getByTestId for elements with no accessible name. getByRole works on the accessibility tree (role and accessible name), so it does not break when the markup or a CSS class changes. As a bonus the test checks accessibility: if a button has no role and name, the locator will not find it. CSS and XPath are tied to the DOM structure and classes, so they are brittle. Example: page.getByRole('button', { name: 'Sign in' }) instead of .btn.btn-primary:nth-child(2). I keep CSS as a fallback when there is no other way.
By default name is matched as a case-insensitive substring, so the Save draft button is found too. In strict mode the action fails with an error about multiple elements. I add exact: true or use a regular expression such as /^Save$/. If there are several such buttons in different blocks, I narrow the scope with a chain from the container.
Before an action Playwright waits by itself until the element is actionable: for click it must be attached to the DOM, visible, stable, not covered and enabled; for fill, visible, enabled and editable. Web-first assertions like expect(locator).toBeVisible() and toHaveText() retry the check until the condition holds or the timeout passes (5 s by default). So the test waits exactly as long as needed. waitForTimeout(3000) is a blind pause: it slows a fast page for nothing, and on a slow one it can still be too short, so the test becomes flaky. Instead I wait for an event: an assertion, waitForResponse or waitForURL. I also avoid expect(await locator.isVisible()).toBe(true): that check runs once and does not retry.
I use expect.poll with a function that queries the API and returns the status, followed by the matcher toBe('PAID'). Poll repeats the call at growing intervals until the condition is met or the timeout expires, so I give it a timeout that fits the real processing time. This is better than a loop with waitForTimeout, because the test doesn't wait longer than needed and gives a clear message on failure.
First I create the promise page.waitForEvent('popup'), then I click the link, and only after that I await the promise. If you start listening after the click, the event may arrive earlier and the test hangs. The tab I get is an ordinary Page, so I then wait for it to load and check the URL with toHaveURL. If the tab is opened not by a specific page, I listen to context.waitForEvent('page').
By default Playwright automatically dismisses native dialogs, so confirm returns false and the deletion is cancelled. I register page.once('dialog') before the click, check the text with dialog.message() and call dialog.accept(). It is important that when a listener exists, the dialog must be closed inside it, otherwise the page hangs. For one expected dialog I use once, so the handler doesn't affect other steps.
I create a worker fixture with the option scope: 'worker' and use workerInfo.workerIndex in the email so workers don't conflict. The built-in request fixture has test scope, so in a worker fixture I create my own API context with playwright.request.newContext(). Before use I create the user, and after it I delete it and call dispose. It is important to remember that after a failure the worker restarts and the fixture will create the user again.
test.step splits a test into business steps, so the report and trace show at which stage it failed, for example Place order. A step can return a value, and with box: true the error points to the step call, not to a line inside the helper. Serial mode runs tests sequentially, skips the rest on a failure, and on a retry restarts the whole group. So I avoid it and make tests independent by preparing data through the API.
waitForResponse and waitForRequest only observe real traffic, while route intercepts a request and lets you replace, change or abort it. To check the payload I create a waitForRequest promise with a predicate on the URL and method, click, and then check request.postDataJSON() with toMatchObject. This way I test the front end's contract without mocks and without interfering with the backend.
I register the route before the action that triggers the request, usually before page.goto, otherwise the request has already gone to the server. I fake it with route.fulfill({ status, json }): the page gets my response and the server never sees the request. I set the scope with a glob pattern (**/api/accounts), a regular expression or a predicate function; inside the handler I can tell methods apart with route.request().method() and pass the rest through route.continue(). A route can be removed with page.unroute. context.route applies to every page of the context, and when both match, page.route wins. For a big recording of traffic there is HAR: routeFromHAR. It matters that page.route does not intercept requests of the request fixture, because that is a separate HTTP client without a page. I do not mock everything: part of E2E should hit the real backend.
By default APIRequestContext doesn't throw on 4xx and 5xx, it just returns the response. This is convenient for negative tests where I expect, say, a 422. So I always check the status explicitly: expect(response).toBeOK() or expect(response.status()).toBe(422). If I want any error to fail the call, for example in data preparation, I set failOnStatusCode: true.
I use the request fixture (APIRequestContext): it sends HTTP requests without a browser, so the test is fast and never starts page. I set baseURL and extraHTTPHeaders with the token in playwright.config. I pass the body with options: data for JSON, form for urlencoded, multipart for files, and the query through params. I check the response explicitly: await expect(res).toBeOK(), res.status() and await res.json() with assertions on the fields. I remember that 4xx and 5xx do not throw, so in negative tests I check the status, and in data setup I turn on failOnStatusCode: true. Playwright fits when the API test lives next to UI tests and shares fixtures and reports, or when the API prepares data for E2E. For a large contract suite, load testing or generation from OpenAPI I pick a dedicated tool.
I prepare data through the API because it is faster and more stable than clicking: I create a user or an order with unique data (for example an email with a UUID) so that parallel tests do not disturb each other. Then in the UI I perform only the flow under test and check the result on the screen. I clean up through the API again, preferably in a fixture teardown so cleanup also runs when the test fails. If the session is needed both ways, I use page.request: it shares cookies with the page. When I need to be sure the UI sent the right request, I create page.waitForResponse or waitForRequest before the click, and after the click I await it and check the status or postDataJSON(). As a result, the UI test does not depend on a long state setup.
All workers act as one account, so tests overwrite each other's data and become flaky. I move to an account per worker: a worker fixture logs in a separate user using parallelIndex and saves the state to a separate file. I log in through the API, because it is faster. I also check the session TTL: if a run is longer than the token's lifetime, there will be 401s at the end.
A setup project is made of ordinary tests, so it has the page and request fixtures, a trace, retries, and it shows up in the HTML report. globalSetup is just a function without any of that, and its failures are hard to debug on CI. I do the cleanup for a setup project with the teardown property. I leave globalSetup for infrastructure without a browser, such as DB migrations or checking that the environment is available.
projects is a set of runs: a browser (chromium, firefox, webkit) or a device, plus separate projects for setup. use holds shared options: baseURL (so tests write page.goto('/login')), trace, screenshot, video, storageState. retries reruns failed tests, usually 1–2 and only in CI. reporter sets the reports: html for people, junit or json for CI. I also often change timeout, workers, fullyParallel, testDir and webServer, which starts the app before the tests. For CI I make the values depend on process.env.CI.
The test timeout is 30 seconds, and it includes beforeEach and test fixtures. The expect timeout is 5 seconds. Actions and navigation have no separate limit, they are bounded only by the test timeout. I set actionTimeout to about 10-15 seconds so a failure points to a specific action. On CI I add globalTimeout and maxFailures, so a hang or a downed environment doesn't eat hours of the runner.
I use a matrix with four shards and fail-fast: false, and each job runs npx playwright test --shard=N/4 with the blob reporter. The tests run in the official Docker image of the same version as the package. The blob reports are uploaded as artifacts even on failure, and a separate job merges them with merge-reports into one HTML. With fullyParallel the shards are balanced by tests, not by files.
npx playwright test --headed shows the browser window. --ui opens UI mode: the test list, a timeline with the steps, DOM snapshots before and after each action, and watch mode. --debug starts the Playwright Inspector: the test runs step by step, you can pause and pick locators; await page.pause() in the code does the same. A trace is recorded with the trace option (on-first-retry is handy in CI). I open it with npx playwright show-trace trace.zip or from the HTML report with npx playwright show-report. The trace holds the steps, network, console and page snapshots, so a failed CI test can be analysed without rerunning it.
First I reproduce it with --repeat-each=20. Then I check isolation: I run it with one worker and with several, and separately from other tests, to find shared data or an order dependency. Next I compare the trace of a successful and a failed run. I classify the cause: the test, the data, the environment, or a real race condition in the application. Until it is fixed, the test goes into quarantine with a ticket and an owner.