Playwright Junior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. Which command creates a new Playwright Test project with a config and an example test?
Correct answer:
npm init playwright@latestThe init command asks a few questions (TypeScript or JavaScript, test folder, GitHub Actions workflow), installs
@playwright/testand browsers, and createsplaywright.config.tswith an example test.2. What does
npx playwright installdo?Correct answer: Downloads the browser builds Playwright needs
Each Playwright version is tested against specific Chromium, Firefox and WebKit builds.
npx playwright installdownloads them;--with-depsalso installs system libraries, which is handy on Linux CI machines.3. Which three browser engines does Playwright Test support out of the box?
Correct answer: Chromium, Firefox and WebKit
Playwright bundles Chromium, Firefox and WebKit builds. It can also run branded Chrome and Edge through the
channeloption.4. Which command runs all Playwright tests in the project?
Correct answer:
npx playwright testnpx playwright testfinds test files intestDir, runs them in parallel across the configured projects, and prints results with the configured reporters.5. How do you run Playwright tests with a visible browser window?
Correct answer: Add the
--headedflagTests run headless by default.
--headedopens real browser windows, which helps when watching what a test does.--debugand UI Mode give even more control.6. How do you run only tests whose title contains "login"?
Correct answer:
npx playwright test -g "login"-g(or--grep) filters tests by a regular expression on the title. You can also pass a file path or afile:lineto run a specific test.7. What does
npx playwright show-reportopen?Correct answer: The HTML report from the last run
The HTML reporter writes
playwright-report/.show-reportserves it locally so you can browse failures, steps, screenshots and traces.8. What is UI Mode (
npx playwright test --ui)?Correct answer: An app to run, watch and time-travel through tests
UI Mode lists tests, runs them in watch mode, and shows each step with DOM snapshots, network and console, so you can see the page at any moment of the test.
9. What does
npx playwright test --debugdo?Correct answer: Opens the Inspector and pauses so you can step through
The Playwright Inspector lets you step through actions, see which element a locator matches and edit locators live.
page.pause()stops at a specific line.10. Where are global settings like
baseURL, retries and projects defined?Correct answer: In
playwright.config.tsThe config file sets the test folder, timeouts, retries, reporters, the
useoptions shared by tests, and the list of projects (browsers or environments).11. What does setting
baseURLin the config allow?Correct answer: Using relative URLs like
page.goto('/login')With
use: { baseURL: 'http://localhost:3000' }, navigation andtoHaveURLcan use relative paths. Changing environments then means changing one setting.12. What is the
pageargument in a Playwright test?test("opens home", async ({ page }) => { await page.goto("/"); });Correct answer: A fixture with a fresh page in an isolated context
pageis a built-in fixture. Each test gets a new browser context and page, so cookies and storage don't leak between tests.13. Why must Playwright actions and assertions be awaited?
Correct answer: They're async; without
awaitthe test may finish firstEvery action talks to the browser asynchronously. A missing
awaitlets the test move on or end before the step is done, which causes flaky or falsely passing tests.14. Which locator does Playwright recommend first for a button?
Correct answer:
page.getByRole('button', { name: 'Save' })Role locators reflect how users and assistive tech see the page. They survive markup and class changes better than CSS or XPath chains.
15. Which locator is best for an input that has a
<label>?Correct answer:
page.getByLabel('Email')getByLabelfinds form controls by their associated label oraria-label. It also checks the form is accessible, unlike positional selectors.16. When is
getByPlaceholdera reasonable choice?Correct answer: For inputs with a placeholder but no label
Labels are better for accessibility, but if a field has only a placeholder,
getByPlaceholder('Search')is still more readable and stable than CSS.17. Which attribute does
getByTestId('submit')look for by default?Correct answer:
data-testidBy default it matches
data-testid="submit". The attribute name can be changed withtestIdAttributein the config, e.g. todata-qa.18. What does
getByText('Welcome')match by default?Correct answer: Elements containing that text, case-insensitive
By default matching is a case-insensitive substring with whitespace normalized. Pass
{ exact: true }for exact matching or a regular expression for patterns.19. Which locator finds an image by its
alttext?Correct answer:
page.getByAltText('Company logo')getByAltTextmatchesimgandareaelements by their alternative text, which also encourages meaningful alt attributes.20. When does Playwright resolve a locator to an element?
Correct answer: Each time an action or assertion uses it
Locators are lazy. They're re-evaluated on every use, so they keep working after re-renders that replace DOM nodes.
21. What happens when a locator used in
click()matches three elements?Correct answer: The action fails with a strictness error
Actions are strict: they require exactly one match, so you don't click the wrong element by accident. Narrow the locator or use
first()/nth()deliberately.22. How do you pick the second row of a list deliberately?
Correct answer:
page.getByRole('listitem').nth(1)nth()is zero-based, withfirst()andlast()as shortcuts. Prefer filtering by content when possible, since order can change.23. How do you find a product card that contains the text "Laptop"?
Correct answer:
page.getByTestId('card').filter({ hasText: 'Laptop' })filter({ hasText })keeps only matches containing the text.filter({ has: locator })keeps those containing a matching child element.24. What does chaining locators like this do?
page.getByRole("dialog").getByRole("button", { name: "OK" })Correct answer: Searches for the button only inside the dialog
Chaining scopes the search to the parent locator. It avoids matching an "OK" button elsewhere on the page.
25. Which method types text into an input, replacing its value?
Correct answer:
fill()fill()focuses the field, clears it and sets the new value in one step, firing aninputevent. It works for inputs, textareas and contenteditable elements.26. When would you use
pressSequentially()instead offill()?Correct answer: When the page reacts to each separate key press
Some widgets (autocomplete, masks) handle individual keydown events.
pressSequentially('abc')types character by character; otherwisefill()is faster and simpler.27. How do you press Enter in a focused search field?
Correct answer:
await locator.press('Enter')press()sends a key or combination likeControl+A.page.keyboardgives lower-level control when needed.28. How do you tick a checkbox in Playwright?
Correct answer:
await locator.check()check()makes sure the box ends up checked, and does nothing if it already is.uncheck()does the opposite;setChecked(bool)handles both.29. How do you pick an option in a native
<select>?Correct answer:
await locator.selectOption('blue')selectOptionaccepts a value, a label ({ label: 'Blue' }) or several values for a multi-select. Custom dropdowns are tested with clicks instead.30. How do you upload a file through an
<input type="file">?Correct answer:
await locator.setInputFiles('data/photo.png')setInputFilessets files on the input without opening the OS dialog. Passing an empty array clears the selection.31. Which method moves the mouse over an element to show its tooltip?
Correct answer:
hover()hover()waits for the element to be actionable and moves the mouse over it, triggering hover styles andmouseenterhandlers.32. What does Playwright check before it clicks an element?
Correct answer: It's visible, stable, enabled and receives events
Actionability checks run automatically and are retried until the timeout. That's why explicit sleeps before actions aren't needed.
33. What does
toHaveTextcheck?await expect(page.getByRole("status")).toHaveText("Saved");Correct answer: The element's text matches, retrying until timeout
Web-first assertions keep retrying until the condition holds or the expect timeout runs out.
toContainTextchecks a substring instead of the full text.34. Which assertion checks the current value of an input?
Correct answer:
await expect(input).toHaveValue('john@x.io')Input values aren't text content, so
toHaveTextwon't see them.toHaveValuereads the livevalueproperty.35. Which assertion checks that the browser is on the dashboard page?
Correct answer:
await expect(page).toHaveURL(/dashboard/)toHaveURLwaits for navigation and accepts a string or a regular expression. Comparingpage.url()directly doesn't retry.36. How do you check that a list shows exactly 3 items?
Correct answer:
await expect(items).toHaveCount(3)toHaveCountretries until the number of matches is right, which handles lists that render gradually.37. How do you assert that an error message is NOT shown?
Correct answer:
await expect(error).not.toBeVisible().notinverts any matcher and still retries.toBeHidden()is an equivalent that passes for hidden or absent elements.38. Which assertion checks that a button is disabled?
Correct answer:
await expect(button).toBeDisabled()toBeDisabledandtoBeEnabledcheck the real disabled state, includingaria-disabledfor some roles, instead of guessing from CSS classes.39. What is the default timeout for
expectassertions in Playwright Test?Correct answer: 5 seconds
Assertions retry for 5 seconds by default (
expect.timeout). The whole test has a separate 30-second timeout by default.40. What is the default timeout for a whole Playwright test?
Correct answer: 30 seconds
Each test, including its hooks and fixtures setup, must finish within
timeout, 30 s by default.test.slow()triples it for known slow tests.41. How do you run only one test while developing?
Correct answer: Temporarily use
test.only(...)test.onlyfocuses a test or describe block. SettingforbidOnly: !!process.env.CIin the config prevents it from slipping into CI.42. What does
test.skip()do?Correct answer: Skips the test, so it doesn't run
test.skipcan be unconditional or conditional, e.g.test.skip(browserName === 'webkit', 'not supported').43. What does
test.fixme()mean?Correct answer: The test is known to be broken and is skipped
fixmedocuments a broken test without deleting it. It appears in the report as skipped, so the problem stays visible.44. What does
test.fail()mean?Correct answer: The test is expected to fail; passing is reported as an error
It marks known bugs: Playwright runs the test and complains if it unexpectedly passes, signalling the bug may be fixed.
45. How can you tag a test to run a smoke subset?
test("checkout", { tag: "@smoke" }, async ({ page }) => { // ... });Correct answer: Add a tag and run
npx playwright test --grep @smokeTags can be set with the
tagoption or written in the title.--grepand--grep-invertfilter by them.46. What does
test.describedo?Correct answer: Groups related tests and their hooks
A describe block groups tests, scopes
beforeEachhooks andtest.useoptions, and shows as a group in the report.47. Where would you put
page.goto('/')that every test in a file needs?Correct answer: In
test.beforeEachbeforeEachruns before every test with that test's fixtures, such aspage. Code at file top level runs once while collecting tests and has no page.48. What do projects in
playwright.config.tsusually describe?Correct answer: Browsers, devices or environments to run tests in
A project is a named set of options. A typical config has chromium, firefox and webkit projects, so every test runs in each browser.
49. How do you run tests only in the Firefox project?
Correct answer:
npx playwright test --project=firefox--projectselects one or more projects by name. Projects can also differ by base URL, device or test folder.50. How do you emulate an iPhone in a Playwright project?
projects: [ { name: "mobile", use: { ...devices["iPhone 15"] } }, ]Correct answer: Spread a preset from
devicesintouseDevice presets set viewport, user agent, touch and device scale factor. They emulate the device in a desktop engine; they're not a real phone.
51. How do you set the browser window size for tests?
Correct answer:
use: { viewport: { width: 1280, height: 720 } }The viewport can be set globally, per project or with
test.use.page.setViewportSizechanges it inside a single test.52. How do you take a screenshot of the page?
Correct answer:
await page.screenshot({ path: 'home.png' })Screenshots can be full page (
fullPage: true) or of one element vialocator.screenshot(). For automatic screenshots on failure, use thescreenshotoption.53. What does
screenshot: 'only-on-failure'inusedo?Correct answer: Attaches a screenshot to the report when a test fails
Failure screenshots help diagnose problems without rerunning. Videos and traces have similar options.
54. Why is
trace: 'on-first-retry'a common setting?Correct answer: It records traces only when a failed test is retried
Traces are very useful but cost time and disk. Recording them on the first retry captures most failures in CI cheaply.
55. What happens to a
window.alert()dialog by default in Playwright?Correct answer: It's dismissed automatically
Dialogs are auto-dismissed unless you add a
page.on('dialog')handler, which can read the message and accept or dismiss it.56. How do you accept a
confirm()dialog?page.on("dialog", (dialog) => dialog.accept()); await page.getByRole("button", { name: "Delete" }).click();Correct answer: Register a dialog handler before the click
Native dialogs aren't part of the DOM, so locators can't reach them. The handler must be registered before the action that opens the dialog.
57. How do you work with a link that opens a new tab?
const pagePromise = context.waitForEvent("page"); await page.getByText("Open docs").click(); const newPage = await pagePromise;Correct answer: Wait for the context's
pageevent while clickingStart waiting before the click so the event isn't missed. The new page is a normal
Pageyou can assert on.58. How do you click a button inside an
<iframe>?Correct answer:
page.frameLocator('#pay').getByRole('button')An iframe has its own document.
frameLocator(orlocator(...).contentFrame()) scopes locators to it.59. How do you test a file download?
const download = page.waitForEvent("download"); await page.getByText("Export CSV").click(); const file = await download;Correct answer: Wait for the
downloadevent and use the resultThe
Downloadobject gives the suggested file name and lets you save the file withsaveAs()to check its contents.60. Which built-in fixture sends HTTP requests without a browser page?
Correct answer:
requestThe
requestfixture is anAPIRequestContext. It usesbaseURLand is great for API tests or for setting up data quickly.61. What does this API test check?
const res = await request.get("/api/users/1"); expect(res.ok()).toBeTruthy(); expect(await res.json()).toMatchObject({ id: 1 });Correct answer: Status is 2xx and the body contains
id: 1ok()is true for 200-299 responses.toMatchObjectchecks a subset of fields, ignoring others.62. Why should each test be able to run on its own?
Correct answer: Tests run in parallel and in any order
Playwright runs files in parallel workers and may retry single tests. A test that needs another one to run first breaks in those cases.
63. What is
@playwright/testcompared to theplaywrightpackage?Correct answer: The test runner with fixtures,
expectand reportersThe
playwrightlibrary only automates browsers.@playwright/testadds the test runner: parallelism, retries, fixtures, assertions, projects and reports.64. Which languages have official Playwright libraries?
Correct answer: JavaScript/TypeScript, Python, Java and .NET
The core API is the same across languages. The full
@playwright/testrunner is for JS/TS; other languages use their own runners like pytest or JUnit.65. What does the Playwright VS Code extension let you do?
Correct answer: Run and debug tests and pick locators from the editor
The extension shows tests in the Testing panel, runs them with a click, sets breakpoints, records new tests and highlights locators in the browser.
66. What does
page.waitForTimeout(2000)do and why avoid it?Correct answer: Waits a fixed 2 s; it's slow and still flaky
Fixed waits are too long when the app is fast and too short when it's slow. Web-first assertions wait exactly as long as needed.
67. What does
toBeVisible()consider visible?Correct answer: A non-empty box and not
visibility: hiddenElements with zero size,
display: noneorvisibility: hiddenare not visible. Being scrolled out of view still counts as visible.68. Which assertion checks an element's attribute?
Correct answer:
await expect(link).toHaveAttribute('href', '/docs')toHaveAttributereads the DOM attribute with retries.toHaveJSPropertychecks a JavaScript property instead.69. What does
getByRole('heading', { name: 'Pricing', exact: true })add withexact?Correct answer: The name must match fully and case-sensitively
Without
exact, the name is a case-insensitive substring, so "Pricing plans" would also match.70. Which assertion checks the page
<title>?Correct answer:
await expect(page).toHaveTitle(/Dashboard/)toHaveTitleretries until the document title matches a string or regular expression.71. Why is
getByRole('link', { name: 'Docs' })better thanlocator('a:nth-child(3)')?Correct answer: It doesn't depend on element order or markup
Positional selectors break when someone adds a link. A role and accessible name describe what the user sees.
72. What does
reporter: 'html'in the config do?Correct answer: Generates an interactive HTML report after the run
Several reporters can be combined, e.g.
listin the terminal plushtml, orjunitfor CI dashboards.73. What does the
webServeroption in the config do?Correct answer: Starts the app before tests and waits for its URL
It runs a command like
npm run dev, waits until the URL responds, and stops it afterwards.reuseExistingServerreuses a server you already started locally.74. How do you pause a test at a certain line to inspect the page?
Correct answer: Add
await page.pause()and run headedpage.pause()opens the Playwright Inspector, where you can explore locators and resume step by step.75. Where should Playwright tests get their test data?
Correct answer: Created by the test or a fixture, not left from earlier runs
Tests that create their own data (via API or fixtures) are independent, repeatable and safe to run in parallel.