Playwright
Interview Questions Answers
Junior Level (0-2 Years)
Focus: Core concepts, basic syntax, setup, and
simple automation.
Q1: What is Playwright and how does it differ from
Selenium? (Frequently Asked)
Answer:
Playwright is an open-source automation library developed by Microsoft for web
testing and scraping. Unlike Selenium, which uses the WebDriver protocol,
Playwright uses the Chrome DevTools Protocol (CDP) natively.
Key Differences:
·
Auto-waiting: Playwright automatically waits for elements
to be ready before performing actions (no need for explicit sleep or WebDriverWait).
·
Language & API: Playwright offers a single API for Chromium,
Firefox, and WebKit, whereas Selenium requires separate drivers.
·
Network Control: Playwright allows for network interception,
mocking, and throttling out of the box.
·
Speed: Playwright is generally faster because it
communicates via WebSocket connections rather than HTTP requests for each
command.
Q2: What are the different types of locators in
Playwright? Which one is recommended and why?
Answer:
Playwright provides several locators, but the recommended ones are user-facing
locators:
1.
page.getByRole() (Most Recommended): Finds elements by ARIA
roles (e.g., button, textbox). This aligns with how users and screen readers
interact with the page, making tests resilient to UI structure changes.
2.
page.getByText(): Finds by text content.
3.
page.getByLabel(): Finds form fields by associated label text.
4.
page.getByPlaceholder(): Finds inputs by placeholder.
5.
page.getByTestId(): Uses data-testid attributes (useful for elements that are hard
to target otherwise).
6.
page.locator(): The general-purpose method for CSS/XPath
selectors.
Why? Playwright's
philosophy is that tests should be resilient. Using getByRole or getByText ensures that if the CSS class
changes but the button text remains "Submit", the test still passes.
Q3: How does Playwright handle auto-waiting?
Answer:
Playwright performs auto-waiting for a range of actionability checks before
performing actions. For example, before clicking an element, Playwright will
wait for:
·
The element to be attached to the
DOM.
·
The element to be visible.
·
The element to be stable (not
moving).
·
The element to receive events (no
other element obscuring it).
·
The element to be enabled.
This eliminates the need for artificial sleep commands. If the check fails,
the action fails with a timeout.
Q4: How do you run tests in parallel?
Answer:
Playwright runs tests in parallel by default using worker processes.
In playwright.config.ts, you can configure:
·
fullyParallel:
true: Runs tests in each file in
parallel.
·
workers: 4: Sets the number of worker processes. If set
to 0,
it uses 50% of CPU cores.
Tests are sharded across workers automatically.
Mid-Level (3-5 Years)
Focus: Advanced configuration, debugging, API
testing, and test architecture.
Q5: How do you handle authentication globally to
avoid logging in before every test? (Frequently Asked)
Answer:
To optimize test execution, Playwright offers Global Setup and Storage
State.
I use setup projects in the config file. I create a
project named setup that performs the login flow once and saves
the session cookies/storage to a file (e.g., storageState.json).
All other test projects then reference this file using storageState: 'storageState.json'.
This way, every test starts with an authenticated session without repeating the
login steps.
Q6: Explain the difference between page.waitForTimeout, page.waitForSelector,
and page.waitForResponse.
Answer:
·
page.waitForTimeout: A hard-coded sleep. This is discouraged in
favor of Playwright's auto-waiting, but sometimes used for debugging.
·
page.waitForSelector: Waits for an element to appear in the DOM or to
be attached. This is a specific version of auto-waiting.
·
page.waitForResponse: Waits for an HTTP response matching a specific
URL or predicate. This is crucial for testing Single Page Applications (SPAs)
where you must wait for API data to load before asserting on the UI.
Q7: How do you handle file uploads and downloads?
Answer:
·
Uploads: Use page.setInputFiles with the file path.
javascript
await
page.locator('input[type="file"]').setInputFiles('path/to/file.pdf');
·
Downloads: Use page.waitForEvent('download') to capture the download event. You can then
save the downloaded file to disk or check its name.
javascript
const [download] = await
Promise.all([
page.waitForEvent('download'),
page.click('button#download')
]);
const
path = await download.path();
Q8: How do you mock API requests or modify
responses?
Answer:
Playwright has powerful network control capabilities using page.route.
I can intercept requests and:
1.
Abort requests (e.g., blocking analytics).
2.
Fulfill with mock data (for testing edge cases
without a backend).
3.
Continue after modifying headers or body.
Example:
javascript
await
page.route('**/api/users',
route => route.fulfill({
status: 200,
body: JSON.stringify([{ id: 1, name: 'Mock
User' }])
}));
Q9: What are fixtures in Playwright? Why are they
better than beforeEach hooks?
Answer:
Fixtures are a powerful concept in Playwright Test that define the environment
state and dependencies for tests.
While beforeEach runs logic before each test, fixtures offer:
·
Encapsulation: They allow you to package reusable setup
(like a logged-in page) into a single variable.
·
Scoping: They support worker-scoped fixtures (run once
per worker) vs. test-scoped (run per test).
·
Composability: You can create fixtures that depend on other
fixtures.
·
Zero-cost: If a test doesn't use a fixture, Playwright
skips the setup, making it more efficient than beforeEach which runs regardless.
Senior Level (5+ Years)
Focus: CI/CD integration, advanced debugging,
custom reporters, and scaling infrastructure.
Q10: How do you integrate Playwright into a CI/CD
pipeline (e.g., Jenkins, GitHub Actions) and handle flaky tests? (Frequently
Asked)
Answer:
Integration:
I configure Playwright to use GitHub Actions with matrix strategies to run
sharded tests across multiple containers to reduce total execution time. Key
configurations include:
·
Using the action.yml to install browsers with
the --with-deps flag
for Linux dependencies.
·
Uploading blob reports to a backend or
using trace.zip artifacts.
Handling Flaky Tests:
1.
Tracing: I enable trace: 'on-first-retry'. If a test fails,
I download the trace viewer to see the DOM snapshots, console logs, and network
requests leading up to the failure.
2.
Retries: I configure retries in the config (e.g., 2 retries
for CI).
3.
expect Config: I
increase timeouts for specific flaky assertions using expect(locator).toBeVisible({ timeout: 10000 }).
4.
Isolation: I ensure tests are completely isolated. If a
test modifies state (e.g., creates an order), I ensure a new user context is
used via browser.newContext() to prevent test order dependency.
Q11: How do you handle iframes, multiple pages, and
pop-ups?
Answer:
·
Iframes: You must interact with the Frame object. Use page.frameLocator() to create a
locator that penetrates the iframe boundary.
javascript
const
frame = page.frameLocator('#iframe-id');
await
frame.locator('button').click();
·
Multiple Pages: Playwright can manage multiple tabs.
Use context.waitForEvent('page') to capture new pages (pop-ups) when a link
opens a new tab.
·
Pop-ups: Similar to pages, I handle pop-ups (dialog
windows) using page.on('dialog') to accept or dismiss them before they break
the test.
Q12: How do you test responsive design or visual regression?
Answer:
Responsive Design:
I use page.setViewportSize to simulate different devices. Playwright
also has a device emulation list built-in:
javascript
import {
devices } from '@playwright/test';
const
iPhone = devices['iPhone 12'];
// Use in context:
await browser.newContext({ ...iPhone });
Visual Regression:
I use expect(page).toHaveScreenshot(). I ensure consistency by:
1.
Freezing
animations: I intercept CSS or inject
styles to disable animations.
2.
Masking dynamic
data: I use toHaveScreenshot({ mask: [page.locator('.timestamp')] }) to mask timestamps or user avatars.
3.
OS Consistency: I run visual tests only in Docker containers
(Linux) to avoid differences between macOS and Windows rendering.
Q13: How do you implement the Page Object Model
(POM) in Playwright? Does Playwright require it?
Answer:
While Playwright does not require the Page Object Model, it is
highly recommended for maintainability.
I implement POM by creating classes that represent pages. However, I leverage
Playwright's strictness and auto-waiting to improve upon traditional POM.
Instead of returning raw elements, I return Locators:
javascript
// Bad: Returns element
handle
get submitButton() { return this.page.locator('#submit'); }
// Good: Returns action
methods that leverage Playwright's resilience
async submitForm(data) {
await this.nameInput.fill(data.name);
await this.submitButton.click();
}
I also use test.use({
storageState }) to handle authentication at the
context level, avoiding the need to pass "logged-in page objects"
manually.
Q14: How do you handle shadow DOM?
Answer:
Playwright has built-in support for shadow DOM. Unlike Selenium, which requires
special drivers, Playwright's locators pierce the shadow DOM by default.
If you need to go through multiple shadow roots, you can chain locators:
javascript
const
button = page.locator('x-details').locator('button');
Alternatively, using page.locator('x-details >> button') (using >> operator) also works to
traverse shadow boundaries.
Summary of "Most Frequently Asked" Questions
If you have limited time, ensure you can answer
these 5 perfectly:
1.
Auto-waiting: Explain that you don't need sleep because Playwright waits for
actionability (visible, stable, enabled).
2.
Locators: Emphasize prioritizing getByRole over CSS/XPath.
3.
Authentication
State: How to store and reuse storageState to speed up test suites.
4.
Debugging: How to use PWDEBUG=1, the Trace Viewer, and --ui mode to fix flaky tests.
5.
CI/CD: How to handle sharding, retries, and
dependencies in a pipeline.
terminology for playwright developer
We need to respond
to the user's request: "terminology for playwright developer". The
user likely wants a list of key terms, concepts, and vocabulary that a
Playwright developer should know. We can provide a glossary-style answer,
covering the essential terminology.
Given
the context, the previous interaction was about interview questions, and now
the user is asking for terminology. We'll produce a concise but comprehensive
list of terms with explanations, suitable for a developer working with
Playwright.
We'll
structure it as a glossary, grouping terms into categories (core concepts,
locators, actions, test runner, configuration, debugging, advanced). We'll aim
for clarity and practical relevance.
We'll keep it in a
similar tone as the previous answer: informative, structured, with bullet
points or headings.
As a Playwright
developer, mastering the terminology is essential for effective communication
and leveraging the full power of the framework. Below is a curated glossary of
key terms, grouped by category.
Core Concepts
|
Term |
Description |
|
Browser |
An instance of a browser (Chromium, Firefox,
WebKit). Playwright launches a browser via playwright.chromium.launch(). |
|
Browser Context |
An isolated incognito-like session within a
browser. Multiple contexts allow testing different authenticated states in
parallel without overlapping data. |
|
Page |
A single tab or window within a browser context.
The primary interface for interacting with the DOM. |
|
Locator |
A representation of an element on the page. Created
via page.locator() or helper methods like getByRole(). Locators are lazy and wait for elements automatically. |
|
Actionability |
Playwright’s set of checks before performing an
action (click, fill, etc.): visible, stable, enabled, editable, etc. |
|
Auto-waiting |
The built-in mechanism that automatically waits
for elements to pass actionability checks before performing actions or
assertions. |
Locators & Selectors
|
Term |
Description |
|
getByRole() |
Recommended locator that finds elements by their
ARIA role (e.g., button, textbox, heading). Most resilient to UI changes. |
|
getByText() |
Locates elements by their text content. Useful
for buttons, links, or any element with visible text. |
|
getByLabel() |
Finds form fields by the text of their
associated <label> element. |
|
getByPlaceholder() |
Locates input elements by their placeholder attribute. |
|
getByTestId() |
Finds elements by a custom data-testid attribute. A fallback when user‑facing
locators aren’t stable. |
|
locator() |
The generic method to create a locator using CSS
selectors, XPath, or text selectors. |
|
>> (chain
operator) |
A shorthand to traverse through shadow DOM or
nested frames (e.g., page.locator('x-details
>> button')). |
|
Term |
Description |
|
.click() |
Performs a click on the element after waiting for actionability. |
|
.fill() |
Clears an input field and types the provided text. |
|
.press() |
Sends a keyboard key press (e.g., Enter, Tab). |
|
.hover() |
Hovers the mouse over an element. |
|
.selectOption() |
Selects one or more options from a <select> element. |
|
.check() / .uncheck() |
Checks or unchecks a checkbox or radio button. |
|
.setInputFiles() |
Uploads files to an <input
type="file">. |
|
.screenshot() |
Captures a screenshot of the page or a specific element. |
Actions & Interactions
Test Runner (Playwright Test)
|
Term |
Description |
|
test |
The main test function used to define a test
case. |
|
expect |
The assertion library bundled with Playwright,
with async matchers like toBeVisible(), toHaveText(), etc. |
|
beforeEach / afterEach |
Hooks that run before/after each test. |
|
beforeAll / afterAll |
Hooks that run once per worker before/after all
tests in a file. |
|
Fixtures |
Reusable test contexts that encapsulate setup and
teardown. Playwright’s fixtures are more powerful than hooks because they can
be scoped (worker/test) and are lazily initialised. |
|
Projects |
Configurable groups of tests (e.g., different
browsers, device emulations) defined in playwright.config.ts. |
|
Workers |
Parallel processes that run tests. Each worker
gets its own browser instance. |
|
Sharding |
Splitting the test suite across multiple
machines/containers to reduce total execution time. |
Configuration & Setup
|
Term |
Description |
|
playwright.config.ts |
The configuration file that defines projects,
timeouts, retries, reporters, etc. |
|
Storage State |
A JSON file containing cookies, localStorage, and
sessionStorage, used to reuse authenticated sessions across tests. |
|
Global Setup |
A script that runs once before all tests (e.g.,
to seed data or log in once). |
|
Trace Viewer |
A GUI tool that records a test run’s DOM
snapshots, console logs, network requests, and actions to help debug
failures. |
|
Reporters |
Output formats for test results. Built‑in: list, line, dot, json, html, blob. |
|
Term |
Description |
|
PWDEBUG=1 |
Environment variable that enables the Playwright inspector, pausing
execution and allowing step‑by‑step debugging. |
|
page.pause() |
Pauses the test and opens the inspector at that point. |
|
UI Mode |
An interactive GUI (npx playwright test --ui) that allows running tests, inspecting traces, and stepping through
code. |
|
Trace Viewer |
(See above) A detailed replay of a test run, accessible via trace.zip artifacts. |
|
Video |
Playwright can record a video of the test execution, often enabled in
CI to visualise failures. |
Debugging & Tooling
Network & Interception
|
Term |
Description |
|
Routing |
Intercepting and modifying network requests
using page.route(). |
|
Fulfill |
Responding to a request with a custom response
(mock data). |
|
Abort |
Cancelling a request (e.g., blocking analytics). |
|
Continue |
Letting the request proceed, optionally modifying
headers or body. |
|
waitForResponse() |
Waits for a specific HTTP response to be
received. Useful for SPAs. |
Advanced Concepts
|
Term |
Description |
|
Shadow DOM |
Encapsulated DOM trees. Playwright locators
pierce shadow roots automatically. |
|
Frame |
A <frame> or <iframe> element. Use frameLocator() to interact inside frames. |
|
Worker (Web
Worker) |
Playwright can listen to and interact with web
workers via page.workers(). |
|
Device Emulation |
Simulating a mobile device (e.g., iPhone 12) by
setting viewport, user agent, touch events, etc. |
|
Visual Regression |
Comparing screenshots using expect(page).toHaveScreenshot(). |
|
Mock |
Stubbing API responses to test edge cases or
remove backend dependencies. |
|
WebSocket |
Playwright can handle WebSocket connections and
messages. |
Understanding these
terms will help you navigate the Playwright documentation, communicate
effectively in your team, and write robust, maintainable tests.
how you will deploy playwright
project
We need to answer:
"how you will deploy playwright project". This likely refers to how
to set up Playwright tests to run in CI/CD, and also possibly deploying the
test artifacts or reports. The user wants a step-by-step guide on deploying
Playwright tests, including typical CI configurations, browser installation,
parallel execution, reporting, etc. We should structure this as a comprehensive
answer covering:
1.
Prerequisites: project structure,
config.
2.
CI/CD platforms: GitHub Actions,
GitLab CI, Jenkins, etc.
3.
Key steps: install dependencies,
install browsers, run tests, handle artifacts (trace, video, screenshots), generate
reports.
4.
Best practices: sharding, retries,
using storage state, caching browsers.
5.
Example for GitHub Actions.
Also
note that "deploy" could be misinterpreted as deploying the
application being tested, but likely they mean deploying the test suite to run
in CI. We'll cover that.
We'll produce a
detailed, step-by-step answer.
Deploying a
Playwright project typically means integrating your tests into a Continuous
Integration (CI) pipeline so they run automatically on code changes, and
potentially publishing test reports or artifacts. Below is a comprehensive
guide covering the entire process, from configuration to execution and
reporting.
1. Prerequisites
Before deploying, ensure your Playwright project is
ready:
·
Configuration file: playwright.config.ts (or .js) with proper settings:
o
Define projects (browsers, device
emulation).
o
Set retries (e.g., retries: 2 for CI).
o
Enable tracing, screenshots, or video
for debugging (e.g., trace:
'on-first-retry').
o
Configure reporters (e.g., html, json, blob for later merging).
·
Package.json
scripts: Typically:
json
"scripts": {
"test": "playwright
test",
"test:ci": "playwright
test --reporter=html,json"
}
·
Environment
variables: Use .env or CI secrets for sensitive
data (API keys, credentials).
2. CI/CD Pipeline Setup
The deployment process varies by CI provider. I'll
focus on GitHub Actions (most common), then highlight
differences for other platforms.
2.1 GitHub Actions Example
Create .github/workflows/playwright.yml:
yaml
name:
Playwright Tests
on:
push:
branches: [
main, develop ]
pull_request:
branches: [
main ]
jobs:
test:
timeout-minutes: 60
runs-on:
ubuntu-latest #
or windows-latest, macos-latest
strategy:
fail-fast: false
matrix:
shard: [1/3,
2/3, 3/3] # shard the test suite
into 3 parts
steps:
- uses:
actions/checkout@v4
- uses:
actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
- name:
Install dependencies
run:
npm ci
- name:
Install Playwright browsers
run:
npx playwright install --with-deps
- name:
Run Playwright tests (sharded)
run:
npx playwright test --shard=${{
matrix.shard }}
- name:
Upload test results (HTML report)
if:
always()
uses: actions/upload-artifact@v4
with:
name:
playwright-report-${{
matrix.shard }}
path:
playwright-report/
- name:
Upload blob report (for merging)
if:
always()
uses:
actions/upload-artifact@v4
with:
name:
blob-report-${{
matrix.shard }}
path:
blob-report/
Key points:
·
--with-deps installs system dependencies required for
browsers (e.g., on Ubuntu).
·
Sharding splits tests across multiple jobs to reduce
execution time. Each shard runs independently, then you can merge reports
later.
·
Artifacts preserve reports even if tests fail.
2.2 Merging Reports (Optional)
If you use sharding, you may want to combine
results into a single HTML report. Create a separate job that runs after all
shards:
yaml
merge-reports:
needs:
test
runs-on:
ubuntu-latest
steps:
- uses:
actions/checkout@v4
- uses:
actions/setup-node@v4
with:
node-version: '18'
- name:
Download all blob reports
uses:
actions/download-artifact@v4
with:
path:
all-blob-reports
- name:
Merge reports
run:
npx playwright merge-reports --reporter=html
./all-blob-reports/blob-report-*
- name:
Upload merged HTML report
uses:
actions/upload-artifact@v4
with:
name: merged-html-report
path:
playwright-report/
2.3 Other CI Platforms
GitLab CI (.gitlab-ci.yml):
yaml
image:
mcr.microsoft.com/playwright:v1.40.0-focal
test:
script:
-
npm ci
-
npx playwright test
artifacts:
when:
always
paths:
-
playwright-report/
reports:
junit:
results.xml
Jenkins (with
NodeJS plugin):
·
Use a pipeline script to install
dependencies, run npx playwright
install, and store test results.
·
Publish HTML reports using the HTML
Publisher plugin.
CircleCI (.circleci/config.yml):
yaml
jobs:
test:
docker:
- image:
mcr.microsoft.com/playwright:v1.40.0-focal
steps:
-
checkout
- run:
npm ci
- run:
npx playwright test
3. Best Practices for Deployment
3.1 Caching
Cache node_modules and Playwright browsers to speed up builds.
In GitHub Actions:
yaml
- uses:
actions/cache@v3
with:
path: |
~/.npm
~/.cache/ms-playwright
key: ${{
runner.os }}-node-${{
hashFiles('package-lock.json') }}
3.2 Use Storage State
If your tests require authentication, do
not log in repeatedly. Instead:
1.
Run a one-time setup that logs in and
saves storageState.json.
2.
Reuse it in all tests via storageState in the config.
3.
In CI, you can generate this state
dynamically (e.g., using a dedicated setup project).
3.3 Environment Isolation
·
Use separate databases/containers for
testing.
·
Avoid hardcoding credentials; use
secrets.
3.4 Retry Logic
Playwright can automatically retry failed tests.
Configure in playwright.config.ts:
ts
retries:
process.env.CI ? 2 : 0,
3.5 Reporting & Notifications
·
Use reporters to output JUnit XML for
test results (e.g., reporter:
[['html'], ['junit', { outputFile: 'results.xml' }]]). This can integrate with CI dashboards.
·
Send notifications (Slack, email) on
failure using CI built-in steps or custom scripts.
3.6 Parallel Execution
Beyond sharding, you can use workers in the config to run tests in
parallel within a single job. For large suites, sharding across multiple CI
machines scales better.
4. Deployment of Test Artifacts
After tests run, you may want to deploy the
test report to a web server for easy access:
·
GitHub Pages: Push the playwright-report folder to the gh-pages branch.
·
Azure Blob Storage
/ AWS S3: Upload artifacts using CLI
commands.
·
Allure Report: Use Playwright's Allure reporter for a more
detailed UI.
Example of deploying to GitHub Pages:
yaml
- name:
Deploy report to GitHub Pages
if:
always()
uses:
peaceiris/actions-gh-pages@v3
with:
github_token: ${{
secrets.GITHUB_TOKEN }}
publish_dir:
./playwright-report
destination_dir: ${{
github.run_id }}
5. Running Playwright on CI Agents
Most CI providers offer Linux, Windows, and macOS
agents. Playwright supports all three. However:
·
Linux is the most cost-effective and fast.
·
Windows/macOS may be needed if you test specific browser
engines (e.g., WebKit on macOS) or Windows-specific behavior.
You can use Docker images provided by
Microsoft: mcr.microsoft.com/playwright:v1.40.0-focal (includes all dependencies and browsers).
This ensures consistency.
Summary
Deploying Playwright involves:
1.
Writing robust
tests with proper configuration.
2.
Choosing a CI
provider and writing a pipeline that:
o
Installs dependencies.
o
Installs Playwright browsers (or uses
a pre-baked Docker image).
o
Runs tests with sharding/parallelism.
o
Captures artifacts (reports, traces,
videos).
o
Merges reports if sharded.
o
Publishes results.
3.
Applying best
practices: caching, storage state, retries,
and secure handling of secrets.
By following this
approach, you ensure that your Playwright tests run reliably and efficiently in
any CI/CD environment.
any other concept that mostly asked
in interview
We need to address
the user's request: "any other concept that mostly asked in
interview". This implies they want additional concepts beyond what's already
covered in the previous responses (which included interview questions,
terminology, and deployment). They likely want a list or explanation of other
frequently asked concepts/topics that could come up in Playwright interviews.
We
should provide a concise but comprehensive list of additional concepts that are
often asked in Playwright interviews, with brief explanations. We'll aim to
supplement the earlier interview questions. Let's think of topics not yet
covered:
·
Playwright vs
Puppeteer vs Cypress (comparison)
·
Handling pop-ups,
multiple tabs, windows
·
Working with
iframes and frames
·
Network mocking,
interception, and request/response modification
·
Visual regression
testing
·
Accessibility
testing
·
Mobile device
emulation
·
Data-driven testing
·
Custom fixtures and
extending test
·
Retries, flaky test
strategies
·
Parallel execution
and sharding
·
Debugging
techniques (trace viewer, inspector, etc.)
·
Continuous
integration best practices
·
Handling
authentication (OAuth, SSO)
·
Generating and
using codegen
·
Playwright vs Selenium
detailed
·
Handling dynamic
content and wait strategies
·
Assertions and
custom matchers
·
Working with
databases, API testing combined with UI
·
Environment
configuration and test data management
·
Reporting and
logging
·
Monorepo support
·
Third-party integrations
(e.g., Allure, Slack)
·
Playwright's
built-in test runner vs using Jest/Mocha
·
Understanding
Playwright's architecture (WebSocket, CDP, etc.)
We
should pick the most commonly asked ones and explain them succinctly. We'll
present as a list or bullet points with brief descriptions.
We'll
maintain a helpful tone, similar to previous responses.
We'll
ensure not to repeat too much from previous content but highlight new aspects.
Let's craft a
response.
You've covered the
core concepts, interview questions, terminology, and deployment. However,
interviewers often dig deeper into specific areas or compare Playwright with
other tools. Here are additional frequently asked concepts that
are likely to come up:
1. Playwright vs Puppeteer vs Cypress
·
Puppeteer: Only Chromium, lower‑level API, great for
scraping but lacks cross‑browser support and the test runner features of
Playwright.
·
Cypress: Excellent developer experience but limited to
Chromium‑based browsers (experimental Firefox) and cannot handle multiple tabs/windows
natively. Playwright supports all browsers and offers better parallelisation
and native iframe handling.
·
Key differentiators
for Playwright: Auto‑waiting, network
interception, mobile emulation, and the ability to run tests in parallel across
multiple contexts.
2. Handling Multiple Pages, Tabs, and Pop‑ups
·
Use browserContext.on('page') to
listen for new pages.
·
For pop‑ups triggered by window.open, capture with context.waitForEvent('page').
·
Example:
js
const [popup] = await
Promise.all([
page.waitForEvent('popup'),
page.click('a[target="_blank"]')
]);
await
popup.waitForLoadState();
3. Working with iframes and Frames
·
Use page.frameLocator(selector) to
create a locator that operates inside an iframe.
·
For nested frames, chain locators.
·
Access frames directly via page.frames() and filter by name or URL.
4. Visual Regression Testing
·
Playwright has built‑in screenshot
comparison: expect(page).toHaveScreenshot().
·
Best practices:
o
Disable animations (CSS or
intercept).
o
Mask dynamic elements (e.g., timestamps)
using toHaveScreenshot({
mask: [locator] }).
o
Run in a consistent environment
(Docker container) to avoid OS rendering differences.
5. Accessibility Testing
·
Playwright can query ARIA roles and
generate accessibility snapshots.
·
Use page.accessibility.snapshot() to
get the accessibility tree.
·
Can integrate with axe‑core or other
libraries via page.addScriptTag() to run automated accessibility checks.
6. Data‑Driven Testing
·
Parameterise tests using test.describe and loops, or use the test.each pattern.
·
Example:
js
const
testData = [
{ username: 'user1', password: 'pass1' },
{ username: 'user2', password: 'pass2' }
];
testData.forEach(({
username, password }) => {
test(`login
as ${username}`, async ({
page }) => {
// ...
});
});
7. Custom Fixtures and Extending the Test
·
Fixtures allow you to encapsulate
setup and teardown.
·
You can extend the base test object to add custom
functionality (e.g., a logged‑in page).
·
Example:
js
const
test = base.extend({
loggedInPage: async ({
browser }, use) => {
const
context = await browser.newContext({ storageState: 'auth.json' });
const
page = await context.newPage();
await use(page);
await
context.close();
}
});
8. Retries and Flaky Test Strategies
·
Configure retries in playwright.config.ts.
·
Use trace: 'on‑first‑retry' to capture
debug data only when a test fails after the first attempt.
·
Employ test.slow() to mark tests that need more
time.
·
Implement custom retry logic for
specific actions (e.g., flaky network calls) using page.waitForFunction or expect.poll.
9. Parallel Execution and Sharding
·
Playwright runs tests in parallel
using workers. Set workers in config.
·
Sharding (splitting tests across multiple CI machines)
is done with --shard=x/n.
·
Use fullyParallel: true to run all
tests in a file concurrently (if they are independent).
10. Debugging Techniques
·
UI Mode: npx
playwright test --ui – interactive GUI with watch
mode.
·
Trace Viewer: Record actions, logs, and DOM snapshots; open
with npx playwright show-trace trace.zip.
·
Inspector: PWDEBUG=1
npx playwright test – step‑by‑step debugging with
breakpoints.
·
page.pause() – programmatic pause to inspect the page.
11. Authentication Strategies
·
OAuth / SSO: Use page.context().addCookies() to inject session cookies, or navigate
through the login flow once and save storage state.
·
For complex flows (e.g., third‑party
login), leverage page.route to mock the authentication response, or use
the --load-storage flag.
12. Network Interception and Mocking
·
page.route() to intercept and modify requests.
·
Use route.fulfill() to return mock data, route.abort() to block resources (e.g.,
analytics), or route.continue() to modify headers.
·
Combine with page.waitForResponse() to wait for
specific API calls before assertions.
13. Environment Configuration
·
Use .env files with dotenv to manage credentials.
·
In playwright.config.ts, access process.env and set baseURL, timeouts, etc.
·
Example:
ts
use: {
baseURL:
process.env.BASE_URL || 'http://localhost:3000',
...(process.env.CI && {
trace: 'on-first-retry' })
}
14. Code Generation
·
npx playwright
codegen opens a browser and records
interactions, generating test code.
·
Useful for quickly creating initial
test scripts.
15. API Testing with Playwright
·
Playwright can be used for API
testing via request.newContext().
·
Example:
js
const
requestContext = await
request.newContext();
const
response = await requestContext.post('https://api.example.com/login', {
data: {
username, password }
});
expect(response.ok()).toBeTruthy();
·
Combine with UI tests to create end‑to‑end
scenarios that reuse API calls for setup.
16. Integration with Test Management Tools
·
Playwright can output JUnit XML (reporter: 'junit') to integrate with tools like
TestRail, Xray, or CI dashboards.
·
Allure reporter is available
via @playwright/test (or allure-playwright) for rich reporting.
17. Monorepo Support
·
Playwright works well in monorepos
(e.g., Nx, Turborepo). Each project can have its own playwright.config.ts.
·
Use projects in config to define different
test suites for different apps.
18. Playwright vs Selenium (Detailed)
·
Protocol: Playwright uses WebSocket‑based CDP; Selenium
uses HTTP‑based WebDriver.
·
Auto‑waiting: Playwright bakes it in; Selenium requires
explicit waits.
·
Browser support: Playwright supports Chromium, Firefox, WebKit
(Safari) with a single API; Selenium requires separate drivers and may have
inconsistent implementations.
·
Network control: Playwright has first‑class network
interception; Selenium lacks this natively.
·
Performance: Playwright is generally faster due to reduced
overhead.
19. Handling Shadow DOM and Custom Elements
·
Playwright locators automatically
pierce open shadow roots.
·
For closed shadow roots, you may need
to evaluate JavaScript using page.evaluate().
20. Mobile Device Emulation
·
Use devices from @playwright/test to emulate specific devices
(viewport, user agent, touch events).
·
Example:
js
const
iPhone = devices['iPhone 12'];
const
context = await browser.newContext({ ...iPhone
});
21. Custom Reporters
·
You can create a custom reporter by
extending Reporter class and implementing onBegin, onTestEnd, etc.
·
Useful for sending results to a
custom dashboard or database.
22. Running Tests in Docker
·
Use the official Playwright Docker
images (mcr.microsoft.com/playwright) which come with all browsers pre‑installed.
·
Example:
bash
docker
run -it --rm --ipc=host
mcr.microsoft.com/playwright:v1.40.0-focal npx playwright test
23. Headless vs Headless Mode
·
By default, Playwright runs in
headless mode on CI. For debugging, you can enable headful (headless: false) or use the --headed flag.
24. Handling Geolocation, Permissions, and Timezone
·
Set permissions in browser
context: context.grantPermissions(['geolocation']).
·
Emulate geolocation: context.setGeolocation({ latitude, longitude }).
·
Override timezone: browser.newContext({ timezoneId: 'America/New_York' }).
25. Web Workers and Service Workers
·
Access workers via page.workers().
·
For service workers, you can wait for
registration and interact with them.
Why these matter: Interviewers
often ask these to gauge your depth of knowledge—not just whether you can write
basic tests, but how you handle real‑world complexity, debug flaky tests, scale
the framework, and integrate with broader systems.
If you prepare
answers for these topics with practical examples, you’ll be well equipped for
senior‑level Playwright interviews.
No comments:
Post a Comment