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. 1. Which command creates a new Playwright Test project with a config and an example test?

    Correct answer: npm init playwright@latest

    The init command asks a few questions (TypeScript or JavaScript, test folder, GitHub Actions workflow), installs @playwright/test and browsers, and creates playwright.config.ts with an example test.

  2. 2. What does npx playwright install do?

    Correct answer: Downloads the browser builds Playwright needs

    Each Playwright version is tested against specific Chromium, Firefox and WebKit builds. npx playwright install downloads them; --with-deps also installs system libraries, which is handy on Linux CI machines.

  3. 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 channel option.

  4. 4. Which command runs all Playwright tests in the project?

    Correct answer: npx playwright test

    npx playwright test finds test files in testDir, runs them in parallel across the configured projects, and prints results with the configured reporters.

  5. 5. How do you run Playwright tests with a visible browser window?

    Correct answer: Add the --headed flag

    Tests run headless by default. --headed opens real browser windows, which helps when watching what a test does. --debug and UI Mode give even more control.

  6. 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 a file:line to run a specific test.

  7. 7. What does npx playwright show-report open?

    Correct answer: The HTML report from the last run

    The HTML reporter writes playwright-report/. show-report serves it locally so you can browse failures, steps, screenshots and traces.

  8. 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. 9. What does npx playwright test --debug do?

    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. 10. Where are global settings like baseURL, retries and projects defined?

    Correct answer: In playwright.config.ts

    The config file sets the test folder, timeouts, retries, reporters, the use options shared by tests, and the list of projects (browsers or environments).

  11. 11. What does setting baseURL in the config allow?

    Correct answer: Using relative URLs like page.goto('/login')

    With use: { baseURL: 'http://localhost:3000' }, navigation and toHaveURL can use relative paths. Changing environments then means changing one setting.

  12. 12. What is the page argument in a Playwright test?

    test("opens home", async ({ page }) => {
      await page.goto("/");
    });

    Correct answer: A fixture with a fresh page in an isolated context

    page is a built-in fixture. Each test gets a new browser context and page, so cookies and storage don't leak between tests.

  13. 13. Why must Playwright actions and assertions be awaited?

    Correct answer: They're async; without await the test may finish first

    Every action talks to the browser asynchronously. A missing await lets the test move on or end before the step is done, which causes flaky or falsely passing tests.

  14. 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. 15. Which locator is best for an input that has a <label>?

    Correct answer: page.getByLabel('Email')

    getByLabel finds form controls by their associated label or aria-label. It also checks the form is accessible, unlike positional selectors.

  16. 16. When is getByPlaceholder a 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. 17. Which attribute does getByTestId('submit') look for by default?

    Correct answer: data-testid

    By default it matches data-testid="submit". The attribute name can be changed with testIdAttribute in the config, e.g. to data-qa.

  18. 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. 19. Which locator finds an image by its alt text?

    Correct answer: page.getByAltText('Company logo')

    getByAltText matches img and area elements by their alternative text, which also encourages meaningful alt attributes.

  20. 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. 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. 22. How do you pick the second row of a list deliberately?

    Correct answer: page.getByRole('listitem').nth(1)

    nth() is zero-based, with first() and last() as shortcuts. Prefer filtering by content when possible, since order can change.

  23. 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. 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. 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 an input event. It works for inputs, textareas and contenteditable elements.

  26. 26. When would you use pressSequentially() instead of fill()?

    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; otherwise fill() is faster and simpler.

  27. 27. How do you press Enter in a focused search field?

    Correct answer: await locator.press('Enter')

    press() sends a key or combination like Control+A. page.keyboard gives lower-level control when needed.

  28. 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. 29. How do you pick an option in a native <select>?

    Correct answer: await locator.selectOption('blue')

    selectOption accepts a value, a label ({ label: 'Blue' }) or several values for a multi-select. Custom dropdowns are tested with clicks instead.

  30. 30. How do you upload a file through an <input type="file">?

    Correct answer: await locator.setInputFiles('data/photo.png')

    setInputFiles sets files on the input without opening the OS dialog. Passing an empty array clears the selection.

  31. 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 and mouseenter handlers.

  32. 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. 33. What does toHaveText check?

    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. toContainText checks a substring instead of the full text.

  34. 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 toHaveText won't see them. toHaveValue reads the live value property.

  35. 35. Which assertion checks that the browser is on the dashboard page?

    Correct answer: await expect(page).toHaveURL(/dashboard/)

    toHaveURL waits for navigation and accepts a string or a regular expression. Comparing page.url() directly doesn't retry.

  36. 36. How do you check that a list shows exactly 3 items?

    Correct answer: await expect(items).toHaveCount(3)

    toHaveCount retries until the number of matches is right, which handles lists that render gradually.

  37. 37. How do you assert that an error message is NOT shown?

    Correct answer: await expect(error).not.toBeVisible()

    .not inverts any matcher and still retries. toBeHidden() is an equivalent that passes for hidden or absent elements.

  38. 38. Which assertion checks that a button is disabled?

    Correct answer: await expect(button).toBeDisabled()

    toBeDisabled and toBeEnabled check the real disabled state, including aria-disabled for some roles, instead of guessing from CSS classes.

  39. 39. What is the default timeout for expect assertions 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. 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. 41. How do you run only one test while developing?

    Correct answer: Temporarily use test.only(...)

    test.only focuses a test or describe block. Setting forbidOnly: !!process.env.CI in the config prevents it from slipping into CI.

  42. 42. What does test.skip() do?

    Correct answer: Skips the test, so it doesn't run

    test.skip can be unconditional or conditional, e.g. test.skip(browserName === 'webkit', 'not supported').

  43. 43. What does test.fixme() mean?

    Correct answer: The test is known to be broken and is skipped

    fixme documents a broken test without deleting it. It appears in the report as skipped, so the problem stays visible.

  44. 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. 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 @smoke

    Tags can be set with the tag option or written in the title. --grep and --grep-invert filter by them.

  46. 46. What does test.describe do?

    Correct answer: Groups related tests and their hooks

    A describe block groups tests, scopes beforeEach hooks and test.use options, and shows as a group in the report.

  47. 47. Where would you put page.goto('/') that every test in a file needs?

    Correct answer: In test.beforeEach

    beforeEach runs before every test with that test's fixtures, such as page. Code at file top level runs once while collecting tests and has no page.

  48. 48. What do projects in playwright.config.ts usually 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. 49. How do you run tests only in the Firefox project?

    Correct answer: npx playwright test --project=firefox

    --project selects one or more projects by name. Projects can also differ by base URL, device or test folder.

  50. 50. How do you emulate an iPhone in a Playwright project?

    projects: [
      { name: "mobile", use: { ...devices["iPhone 15"] } },
    ]

    Correct answer: Spread a preset from devices into use

    Device 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. 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.setViewportSize changes it inside a single test.

  52. 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 via locator.screenshot(). For automatic screenshots on failure, use the screenshot option.

  53. 53. What does screenshot: 'only-on-failure' in use do?

    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. 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. 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. 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. 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 page event while clicking

    Start waiting before the click so the event isn't missed. The new page is a normal Page you can assert on.

  58. 58. How do you click a button inside an <iframe>?

    Correct answer: page.frameLocator('#pay').getByRole('button')

    An iframe has its own document. frameLocator (or locator(...).contentFrame()) scopes locators to it.

  59. 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 download event and use the result

    The Download object gives the suggested file name and lets you save the file with saveAs() to check its contents.

  60. 60. Which built-in fixture sends HTTP requests without a browser page?

    Correct answer: request

    The request fixture is an APIRequestContext. It uses baseURL and is great for API tests or for setting up data quickly.

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

    ok() is true for 200-299 responses. toMatchObject checks a subset of fields, ignoring others.

  62. 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. 63. What is @playwright/test compared to the playwright package?

    Correct answer: The test runner with fixtures, expect and reporters

    The playwright library only automates browsers. @playwright/test adds the test runner: parallelism, retries, fixtures, assertions, projects and reports.

  64. 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/test runner is for JS/TS; other languages use their own runners like pytest or JUnit.

  65. 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. 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. 67. What does toBeVisible() consider visible?

    Correct answer: A non-empty box and not visibility: hidden

    Elements with zero size, display: none or visibility: hidden are not visible. Being scrolled out of view still counts as visible.

  68. 68. Which assertion checks an element's attribute?

    Correct answer: await expect(link).toHaveAttribute('href', '/docs')

    toHaveAttribute reads the DOM attribute with retries. toHaveJSProperty checks a JavaScript property instead.

  69. 69. What does getByRole('heading', { name: 'Pricing', exact: true }) add with exact?

    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. 70. Which assertion checks the page <title>?

    Correct answer: await expect(page).toHaveTitle(/Dashboard/)

    toHaveTitle retries until the document title matches a string or regular expression.

  71. 71. Why is getByRole('link', { name: 'Docs' }) better than locator('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. 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. list in the terminal plus html, or junit for CI dashboards.

  73. 73. What does the webServer option 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. reuseExistingServer reuses a server you already started locally.

  74. 74. How do you pause a test at a certain line to inspect the page?

    Correct answer: Add await page.pause() and run headed

    page.pause() opens the Playwright Inspector, where you can explore locators and resume step by step.

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