A curated set of commonly-asked conceptual Playwright interview questions, with elaborated explanations, syntax, and CLI commands — the same ones our students use to prep for QA automation interviews.
1. What is the difference between Browser, Context, and Page?
- Browser — a single running instance of Chromium/Firefox/WebKit. Launching a browser is expensive, so Playwright reuses one browser across many tests.
- BrowserContext — an isolated, incognito-like session inside a browser. Each context has its own cookies, localStorage, and cache — nothing leaks between contexts. This is what makes Playwright tests parallel-safe without needing separate browser installs.
- Page — a single tab within a context. A context can have multiple pages (tabs).
const browser = await chromium.launch();
const context = await browser.newContext(); // isolated session
const page = await context.newPage(); // a tab
2. What are the different timeout types in Playwright, and how are they configured?
Playwright has five distinct timeout layers, each solving a different problem:
| Timeout type | What it covers | How to set |
|---|---|---|
| Test timeout | Total time a single test is allowed to run | test.setTimeout(60000) or config timeout: 60000 |
| Action timeout | Time for a single action (click, fill, check) to become actionable | { timeout: 5000 } per call, or config use: { actionTimeout } |
| Navigation timeout | Time for goto, waitForNavigation, etc. | { timeout: 15000 } per call, or config use: { navigationTimeout } |
| Assertion timeout | Time expect() retries before failing (web-first assertions) | config expect: { timeout: 10000 } |
| Global timeout | Time for the entire test run (all tests combined) | config globalTimeout: 3600000 |
// playwright.config.js
export default {
timeout: 30000, // per-test
expect: { timeout: 5000 }, // per-assertion
use: {
actionTimeout: 10000,
navigationTimeout: 30000,
},
globalTimeout: 3600000,
};
3. How does Playwright achieve auto-waiting, and what makes locators “resilient”?
Locators are lazy — they don’t resolve to an element until an action is performed, and they re-query the DOM every single time. Before acting, Playwright automatically waits for the element to be attached, visible, stable (not animating), enabled, and receiving events. This eliminates the flaky Thread.sleep() / explicit-wait patterns common in Selenium.
await page.getByRole('button', { name: 'Submit' }).click(); // auto-waits internally
Locators are also resilient to DOM re-renders (e.g., React re-mounting a component), whereas ElementHandle references can go stale.
4. How do you run tests in parallel, and how do you control the number of workers?
Playwright parallelizes at the test file level by default — each file runs in its own worker process. Workers are isolated OS processes (not just threads), so there’s no shared state risk.
// playwright.config.js
export default { workers: 4 };
CLI overrides:
npx playwright test --workers=4 # run with 4 parallel workers
npx playwright test --workers=1 # force serial execution
npx playwright test --workers=50% # use 50% of available CPU cores
To force tests within a single file to run serially (e.g., shared state), use test.describe.serial().
5. How do you handle multiple tabs or popup windows?
Listen for the page event on the context (new tab) or the popup event on the triggering page (window.open-style popups), and capture the new Page object.
const [newPage] = await Promise.all([
context.waitForEvent('page'),
page.click('#open-new-tab'),
]);
await newPage.waitForLoadState();
6. How do you interact with elements inside an iframe?
Use frameLocator(), which scopes all locators to inside the iframe and still auto-waits — no manual switchTo().frame() needed like in Selenium.
await page.frameLocator('#paymentFrame').getByRole('button', { name: 'Pay Now' }).click();
7. toBeAttached() vs toBeVisible() — what’s the difference?
- toBeAttached() — element exists in the DOM (could be hidden via CSS, off-screen, visibility:hidden, or zero-opacity).
- toBeVisible() — element exists and is actually rendered/visible to a user (has size, no display:none, no visibility:hidden).
await expect(locator).toBeAttached(); // just present in DOM
await expect(locator).toBeVisible(); // present AND visible
Common trap: elements can be attached but not visible (e.g., a collapsed accordion panel) — asserting the wrong one causes false positives.
8. How does Playwright support API testing and network interception?
Two distinct capabilities:
- APIRequestContext — pure API testing without a browser at all (fast, ideal for setup/teardown or backend contract tests).
- page.route() — intercept, modify, or mock network requests made by the browser during UI tests.
// Pure API call
const response = await request.get('https://api.example.com/users/1');
// Mocking a network response during a UI test
await page.route('**/api/users', route =>
route.fulfill({ json: [{ id: 1, name: 'Rahul' }] })
);
9. What is the Page Object Model (POM) and why is it recommended?
POM encapsulates a page’s locators and interactions inside a class, so tests read as business logic rather than raw selectors. This decouples test scripts from UI structure — if a locator changes, you fix it in one place.
class LoginPage {
constructor(page) { this.page = page; }
async login(username, password) {
await this.page.getByLabel('Username').fill(username);
await this.page.getByLabel('Password').fill(password);
await this.page.getByRole('button', { name: 'Login' }).click();
}
}
10. How do you run a specific test file, test, or tag from the command line?
npx playwright test tests/login.spec.js # run one file
npx playwright test -g "should login successfully" # run by test name (grep)
npx playwright test --grep @smoke # run by tag
npx playwright test --grep-invert @slow # exclude a tag
npx playwright test --project=chromium # run only on one browser
Tags are just conventions in the test title, e.g. test(‘login works @smoke’, async () => {}).
11. What is the difference between –headed and –debug mode?
- –headed — runs the browser with a visible UI instead of headless (useful to visually watch execution).
- –debug — opens the Playwright Inspector, pauses before each action, and lets you step through the test line by line.
npx playwright test --headed
npx playwright test --debug
npx playwright test tests/login.spec.js --debug # debug a single file
12. How do you generate and view an HTML test report / trace?
Playwright’s trace viewer captures a full timeline (DOM snapshots, network, console, screenshots) for failed (or all) tests — critical for debugging CI failures without reproducing locally.
npx playwright show-report # open last HTML report
npx playwright show-trace trace.zip # open a specific trace file
// playwright.config.js
use: { trace: 'on-first-retry' } // capture trace only when a test retries after failing
13. How does Playwright handle retries, and how do you configure them?
Retries re-run a failed test up to N more times before marking it failed — useful for smoothing over environment flakiness in CI, though it shouldn’t be a substitute for fixing genuinely flaky tests.
// playwright.config.js
export default { retries: 2 };
npx playwright test --retries=2
14. How do you run tests across multiple browsers/projects?
Projects in the config define browser + settings combinations; –project on the CLI filters which ones run.
// playwright.config.js
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
]
npx playwright test # runs all projects
npx playwright test --project=firefox # only Firefox
npx playwright test --project=chromium --project=webkit # multiple
15. How does Playwright handle authentication state reuse across tests?
Instead of logging in through the UI in every test (slow, flaky), Playwright can save browser storage state (cookies + localStorage) once and reuse it — a huge speed win for suites with many authenticated tests.
// Save state once (e.g. in a setup project)
await page.context().storageState({ path: 'auth.json' });
// Reuse in config
use: { storageState: 'auth.json' }
16. What’s the difference between soft assertions and regular assertions?
- Regular expect() — throws immediately and stops the test on failure.
- expect.soft() — logs the failure but lets the test continue, so you can see all failures in one run instead of stopping at the first.
await expect.soft(page.getByText('Welcome')).toBeVisible();
await expect.soft(page.getByText('Dashboard')).toBeVisible();
// test continues even if the first soft assertion fails; final result still reflects it
17. How do you run only failed tests from the last run?
npx playwright test --last-failed
Useful in CI-debug loops or after fixing a batch of flaky failures — avoids re-running the entire (often slow) suite.
18. How do you update visual snapshots / handle visual regression testing?
Playwright supports pixel-level screenshot comparison via toHaveScreenshot(). Baselines are stored per-OS/browser since rendering differs subtly across platforms.
await expect(page).toHaveScreenshot('homepage.png');
npx playwright test --update-snapshots # regenerate baseline images after an intentional UI change
19. What are fixtures in Playwright Test, and how do you create a custom one with test.extend()?
Fixtures are Playwright Test’s mechanism for setting up and tearing down state for tests — built-in fixtures like page, context, and browser are already fixtures, created fresh per test/worker as needed.
import { test as base } from '@playwright/test';
export const test = base.extend({
loggedInPage: async ({ page }, use) => {
await page.goto('/login');
await page.getByLabel('Username').fill('rahul');
await page.getByLabel('Password').fill('learning');
await page.getByRole('button', { name: 'Sign In' }).click();
await use(page); // hand control to the test
// any code here runs as teardown after the test finishes
},
});
// usage in a spec file:
test('dashboard loads', async ({ loggedInPage }) => {
await expect(loggedInPage.getByText('Welcome')).toBeVisible();
});
This mirrors pytest fixtures conceptually — reusable setup/teardown injected by parameter name instead of repeated in every test’s beforeEach.
20. How do you handle file uploads and downloads in Playwright?
Upload — set files directly on the input, no OS dialogs involved:
await page.locator("input[type='file']").setInputFiles('resume.pdf');
Download — wrap the trigger and save the result:
const [download] = await Promise.all([
page.waitForEvent('download'),
page.click('#download-report'),
]);
await download.saveAs('reports/report.xlsx');
Validate via download.suggestedFilename(), checking the saved file exists and has non-zero size, or opening it to assert contents.
21. How do you handle JavaScript dialogs (alert, confirm, prompt) in Playwright?
page.on('dialog', dialog => dialog.accept()); // OK / accept
page.on('dialog', dialog => dialog.dismiss()); // Cancel
page.on('dialog', dialog => dialog.accept('Rahul')); // prompt with input text
await page.click('#trigger-alert');
You can also read dialog.message() to assert the alert text. If no handler is registered, Playwright auto-dismisses dialogs so tests don’t hang.
22. Do Playwright tests run in serial or parallel by default? A deep dive into workers, fullyParallel and fixture scope
This one question can fill a 30-minute interview round. The short answer is parallel, and that answer leads to many follow-up questions: what parallel actually means, what a worker is, how many you get, how to change the unit of parallelism, and how fixture scope fits in. This deep dive walks through each of them in order.
What does “parallel” actually mean?
Take a suite with 4 test files, 3 tests in each file, 12 tests in total. What does “parallel” mean for this suite?
| Option | What it claims |
|---|---|
| A | All 12 tests run at the same time |
| B | The 4 files run at the same time, and the 3 tests inside each file run one after another |
The answer is B, with one limit: the number of files that really run together is decided by workers.
What is a worker?
A worker is a separate Node.js process that Playwright starts to run your tests. Workers run in parallel with each other, and tests inside one worker run one after another. Workers share no memory, which is why they can run at the same time without interfering.
So the parallelism is between workers, not between tests inside a worker. A worker takes one test, finishes it, then takes the next. With –workers=1, all 12 tests run sequentially in one process.
Example with 4 files, 3 tests each and 2 workers: Playwright keeps a queue of files. Each worker takes one file, runs its 3 tests in order, then asks the queue for the next file.
Queue: file1, file2, file3, file4 (3 tests each)
Worker 0: file1 [t1 → t2 → t3] → file3 [t1 → t2 → t3] = 6 tests
Worker 1: file2 [t1 → t2 → t3] → file4 [t1 → t2 → t3] = 6 tests
This is one possible outcome, not a fixed plan. Whichever worker becomes free first takes the next file, so slow tests change who gets what.
| Workers | What happens to the 12 tests |
|---|---|
| 1 | All 12 run one after another |
| 2 | 2 files at a time, each worker handles 2 files |
| 4 | 4 files at a time, one file per worker |
| 8 | Still only 4 workers start, because there are only 4 files |
Does every test get a fresh browser, or a fresh context?
A worker does not open a new browser for every test. It launches one browser and reuses it. Only the context, which is incognito-like, is created fresh for each test.
Worker 0 (Node process)
└── Browser (Chromium) ← launched ONCE per worker
├── Context for test 1 → closed
├── Context for test 2 → closed
└── Context for test 3 → closed
Launching a browser takes around a second. Creating a context takes a few milliseconds. Playwright pays the expensive cost once per worker and the cheap cost once per test.
| Job | Cost | |
|---|---|---|
| Context | Isolation: fresh cookies, localStorage and session, so test 2 cannot be affected by test 1 | Very cheap |
| Worker | Parallelism: a separate process running its own tests at the same time as other workers | Higher: a Node process plus a browser |
In one line: the context answers “will my tests interfere?” and the worker answers “how many run at the same time?” Contexts keep tests independent, and that independence is what makes it safe to spread them across workers.
How many workers do you get if you set nothing?
Playwright uses half of your machine’s logical CPU cores, rounded down, with a minimum of 1. The run prints the number at the top, for example “Running 12 tests using 4 workers”.
| Logical cores | Default workers |
|---|---|
| 4 | 2 |
| 8 | 4 |
| 16 | 8 |
# check your logical core count, then halve it
node -e "console.log(require('os').cpus().length)"
Two things change the number. First, the amount of work: Playwright never starts more workers than it has units of work, so with the default mode and only 2 test files you get at most 2 workers, even on a 16-core machine. Second, your config file. The config generated by npx playwright init contains this line:
workers: process.env.CI ? 1 : undefined,
undefined means “use the default”, so your laptop uses half the cores. On CI, where the CI variable is set, it forces 1 worker. This is a classic interview scenario: tests take 2 minutes locally and 10 minutes on CI, and this line is the cause.
You can set the count yourself in the config, and npx playwright test –workers=6 on the command line overrides the config file:
workers: 4, // fixed number
workers: '50%', // percentage of logical cores, same as the default
workers: '100%', // every core
More workers is not always faster. Each worker is a Node process plus a browser, so going past your CPU or RAM makes tests slower and flakier. Half the cores is a safe default because browsers are heavy.
Can tests inside one file also run in parallel?
By default (fullyParallel: false), Playwright hands a whole file to a worker. Test files run in parallel, and the tests inside one file run sequentially in the same worker. With 4 files and 4 workers, each worker takes one file and runs its 3 tests in order:
Worker 0: file1 [t1 → t2 → t3]
Worker 1: file2 [t1 → t2 → t3]
Worker 2: file3 [t1 → t2 → t3]
Worker 3: file4 [t1 → t2 → t3]
The 3 tests of one file never split across workers. The catch: if you have 1 file with 12 tests, only one worker does the work, because the file is the unit. Useful parallelism is capped at the number of files.
Set fullyParallel: true and the unit of work becomes a single test. All 12 tests go into the queue and each free worker takes the next one, even when its siblings from the same file are running elsewhere.
// playwright.config.ts
export default defineConfig({
workers: 3,
fullyParallel: true,
});
Worker 0: file1-t1 → file2-t2 → file4-t1 → ...
Worker 1: file1-t2 → file3-t1 → file2-t3 → ...
Worker 2: file1-t3 → file2-t1 → file3-t2 → ...
Again, this is one possible outcome, because assignment is dynamic.
| Default | fullyParallel: true | |
|---|---|---|
| Unit handed to a worker | A whole file | A single test |
| Tests within one file | Sequential, same worker | Can spread across workers |
| Most workers that can be busy | Number of files | Number of tests |
| Hidden risk | Tests may quietly depend on each other’s order | That dependency breaks immediately, which helps you find it |
What if you want parallel (or serial) for just one file or group?
You do not have to pick one mode for the whole suite. test.describe.configure changes the mode for a single describe block, or for a whole file when you call it at the top level.
import { test } from '@playwright/test';
test.describe('Product search', () => {
test.describe.configure({ mode: 'parallel' }); // tests may spread across workers
test('search by name', async ({ page }) => { /* ... */ });
test('search by category', async ({ page }) => { /* ... */ });
});
test.describe('Checkout flow', () => {
test.describe.configure({ mode: 'serial' }); // run in order, in one worker
test('add to cart', async ({ page }) => { /* ... */ });
test('pay', async ({ page }) => { /* ... */ });
test('verify order', async ({ page }) => { /* ... */ });
});
| Mode | Behavior |
|---|---|
| parallel | Tests in the group can run in different workers at the same time, like fullyParallel but for this group only |
| serial | Tests run in order in one worker. If one fails, the rest of the group is skipped, and a retry re-runs the whole group together |
Use serial only for a genuinely dependent flow such as create order, pay, verify. Independent tests are faster and easier to debug, so treat serial as the exception. The two settings combine well: keep fullyParallel: true in the config for speed, and mark only the few dependent groups as serial.
Custom fixtures: why use them over beforeEach/afterEach?
A fixture is setup that Playwright builds for your test, hands to it, and cleans up afterward. It is declared with test.extend and injected by name into the test signature. Code before await use(value) is setup, and code after it is teardown.
Setup is lazy (it runs only for tests that request the fixture), typed and composable (fixtures can depend on other fixtures), and teardown lives next to setup rather than in a distant afterEach. Two extras interviewers like: { auto: true } runs a fixture for every test without it being requested, and mergeTests combines fixture sets from different files.
Test-scoped vs worker-scoped fixtures
Scope decides how often a fixture is built: once per test or once per worker. This is where the browser vs context split pays off.
- Test scope (default) — set up before each test and torn down after it. Use it for anything that must be clean every time.
- Worker scope — set up once when the worker first needs it, shared by every test that worker runs, torn down when the worker shuts down. Use it for expensive things that are safe to share, such as a DB connection, an API token, a seeded database or a dedicated user account per worker.
Worker scope is declared with the array form [fn, { scope: ‘worker’ }] and the generic base.extend<TestFixtures, WorkerFixtures>:
// fixtures.ts
import { test as base } from '@playwright/test';
export const test = base.extend<
{ orderData: string }, // test-scoped fixtures
{ dbConnection: string } // worker-scoped fixtures
>({
// Test scope (the default)
orderData: async ({}, use) => {
console.log(' TEST fixture setup');
await use('order-123'); // the test runs here
console.log(' TEST fixture teardown');
},
// Worker scope: array form with the scope option
dbConnection: [async ({}, use, workerInfo) => {
console.log(`WORKER ${workerInfo.workerIndex} setup`);
await use('db-connection');
console.log(`WORKER ${workerInfo.workerIndex} teardown`);
}, { scope: 'worker' }],
});
export { expect } from '@playwright/test';
// file1.spec.ts
import { test } from './fixtures';
test('t1', async ({ orderData, dbConnection }) => { console.log(' running t1'); });
test('t2', async ({ orderData, dbConnection }) => { console.log(' running t2'); });
test('t3', async ({ orderData, dbConnection }) => { console.log(' running t3'); });
What one worker prints for this file:
WORKER 0 setup ← once
TEST fixture setup
running t1
TEST fixture teardown
TEST fixture setup
running t2
TEST fixture teardown
TEST fixture setup
running t3
TEST fixture teardown
WORKER 0 teardown ← once, when the worker shuts down
Back to the 4 files x 3 tests suite running on 2 workers:
| Fixture | Times it runs |
|---|---|
| Test-scoped (orderData) | 12, once per test |
| Worker-scoped (dbConnection) | 2, once per worker |
Fixture rules and common traps
- Fixtures are lazy — a worker fixture is created only when some test in that worker asks for it. Add { auto: true } in the options to run a fixture for every test even when it is not requested.
- A failed test restarts the worker — Playwright discards that worker and starts a new one, and the replacement runs its worker fixtures again. So “once per worker” can happen more times than the worker count.
- No mutable state in worker scope — putting something like a shared logged-in page in worker scope brings back coupling between tests.
- Scope direction — a worker-scoped fixture can’t depend on a test-scoped one.
Interview cheat sheet
Each answer below is short enough to say out loud in an interview.
| Question | Crisp answer |
|---|---|
| Do Playwright tests run in serial or parallel by default? | Parallel. Test files run in parallel across workers, and tests inside one file run sequentially in the same worker. |
| What is a worker? | A separate Node.js process that runs tests one at a time. Workers run in parallel with each other and share no memory. |
| Does parallel mean tests or workers run together? | Workers run together. The tests inside a single worker never overlap. |
| How many workers do you get by default? | Half of the logical CPU cores, and never more than the number of files (or tests, with fullyParallel). |
| Worker vs browser context? | The context gives each test a clean, isolated state. The worker gives parallelism, and it launches one browser reused by all its tests. |
| How do you run tests inside one file in parallel? | Set fullyParallel: true in the config, or test.describe.configure({ mode: ‘parallel’ }) for one group. |
| How do you force tests to run in order? | test.describe.configure({ mode: ‘serial’ }). If one test fails, the rest of the group are skipped. |
| Why are tests slower on CI than locally? | The generated config often sets workers: process.env.CI ? 1 : undefined, which forces a single worker on CI. |
| What are the fixture scopes? | Test scope (default) runs once per test. Worker scope runs once per worker and is shared by that worker’s tests. |
| Why is browser worker-scoped and page test-scoped? | Launching a browser is expensive, so it is done once per worker. A page must be fresh for each test to keep tests independent. |
| Are worker fixtures shared across workers? | No. Each worker process creates its own copy. |
| What happens to the worker when a test fails? | Playwright discards it and starts a new worker, so worker fixtures run again. |
From One Slow Test Run to Parallel CI
An interview story: Playwright, GitHub Actions, Shards, Azure and Docker
1. What is CI/CD, and why do automation engineers care about it?
CI, Continuous Integration, means every time a developer pushes code, an automated process builds it and runs the tests immediately, instead of someone remembering to test before a release. CD, Continuous Delivery or Deployment, extends that: code that passes the checks is automatically prepared for release, or released.
Automated tests are the gatekeeper in this process. If the tests fail, the change does not move forward. That makes the test run part of every single push, which is exactly why how fast it runs matters so much.
On GitHub, CI/CD is implemented with GitHub Actions.
2. How do you set up CI for Playwright tests using GitHub Actions?
You add a workflow file, a YAML file inside .github/workflows in the repository. Four ideas make up every workflow:
- on — the trigger. For example, run on every push and pull request to main.
- jobs — independent units of work. A workflow can have one job or many.
- runs-on — which machine the job runs on, such as ubuntu-latest.
- steps — the ordered actions inside a job. A step either reuses a ready-made action with uses (like actions/checkout) or runs a command with run (like npm ci).
A basic Playwright workflow checks out the code, installs Node, installs dependencies, runs npx playwright test, and uploads the report as an artifact.
Where do the tests physically execute?
3. Where exactly do the Playwright tests run, and what goes wrong as the suite grows?
They run on a GitHub-hosted runner: a fresh virtual machine that GitHub creates for the job and destroys when it finishes. It starts empty, which is why every job must check out the code and install dependencies from scratch. Nothing carries over from one job to the next.
That machine is small, with only a few CPU cores. Playwright can use several worker processes, but workers share those cores, so the speed-up stops quickly. Developers end up waiting on every pull request.
What are the options?
4. How can you run Playwright tests beyond the limits of a single runner?
There are two approaches, and they scale in different ways:
- Cloud-hosted browsers on Azure — The runner keeps executing the test runner, but the browsers run in Azure’s cloud grid, so you are no longer limited by the runner’s CPU.
- Shards on GitHub — Split the suite into slices and run each slice on its own GitHub runner, all at the same time. You use GitHub’s own machines, just several at once.
The second option uses infrastructure the team already pays for, so start there. What exactly is a shard, and how does the splitting happen?
5. How does sharding actually happen? Explain with a small example.
Sharding is a combination of two separate pieces, each doing a different job.
- GitHub’s strategy.matrix — a job generator. It takes lists of values and creates one job for every combination.
- Playwright’s –shard=X/N flag — tells the test runner which slice of the suite to execute.
Consider this matrix:
strategy:
matrix:
shardIndex: [1, 2, 3, 4]
shardTotal: [4]
shardIndex has four values, so it is the one that creates jobs. shardTotal has a single value, so it creates no extra jobs; it is a constant stamped onto every job so each one knows the suite is being cut into 4 pieces. Four values times one value gives 4 parallel jobs, and each runs a different command:
| Job | shardIndex | shardTotal | Command |
|---|---|---|---|
| Job 1 | 1 | 4 | –shard=1/4 |
| Job 2 | 2 | 4 | –shard=2/4 |
| Job 3 | 3 | 4 | –shard=3/4 |
| Job 4 | 4 | 4 | –shard=4/4 |
The flag is not a fraction. Read –shard=3/4 as “shard number 3 out of 4 total,” the same way you would write “page 3 of 4.” The number after the slash decides how many equal buckets the suite is divided into; the number before the slash only picks which bucket this run executes.
With 20 tests and 4 shards, each shard runs about 5 tests, and together they cover all 20 exactly once. Change the matrix to shardIndex: [1, 2, 3, 4, 5] with shardTotal: [5] and you get 5 machines running about 4 tests each. The rule is simple: tests per shard = total tests ÷ shardTotal.
Each shard is a fully independent job with its own machine, its own checkout, and its own browser process. They do not talk to each other while running.
Each of those machines still has several CPU cores. Playwright also has a workers setting. Where do workers fit in?
6. If we combine shards with workers, which one decides the parallelism first?
They work at two different levels, and shards come first.
- Shards — split the suite across machines. This is decided by the GitHub matrix before any test starts.
- Workers — run tests in parallel inside one machine. Once a shard’s slice of tests has landed on its runner, –workers=N decides how many of those tests execute at the same time on that runner’s cores.
Nothing is handed from workers to shards. Shard 3 receives its slice, and then that machine’s workers work through it.
Total tests running at once = number of shards × workers per shard. Five shards with one worker each means 5 tests at a time; five shards with two workers each means 10.
Because a standard runner has only a few cores, adding many workers to one shard stops helping quickly. In CI, more machines through sharding is the main lever, and workers are a secondary tuning knob.
Now there are 4 machines, each finishing with its own results. The team wants one report. How do you get it?
7. Each shard produces its own results. How do you end up with one report?
Each shard runs with the blob reporter, which writes a mergeable intermediate report, and uploads it as an artifact with a unique name that includes the shard index. If the names were identical, the uploads would overwrite each other.
Then a second job, merge-reports, uses needs: [test] so it starts only after all shards finish. That job downloads every blob-report-* artifact into one folder and runs npx playwright merge-reports to produce a single HTML report.
So why would any team choose the other option? How does Azure achieve the same parallelism?
8. How do you achieve the same parallel speed-up using Azure?
There is no sharding matrix here and no browser installation — the browsers are already provisioned in the cloud. Because the heavy work is not happening on the runner’s CPU, the workers setting can be raised far beyond what a small runner could handle.
Both approaches give parallelism. So how do they actually compare, and where does the cost fit in?
9. What are the differences and advantages of GitHub sharding versus Azure, including cost?
| GitHub shards | Azure cloud browsers | |
|---|---|---|
| Where tests run | Several GitHub runners at once | Browsers in Azure; runner triggers them |
| Browser setup | You install browsers on every shard | Nothing to install; already provisioned |
| How it scales | More shards, up to the account’s concurrent-job limit | Elastic; scales past runner and job limits |
| Billing | GitHub Actions minutes, usually already paid for | A separate additional service bill |
| Result merging | You build the merge job yourself | Handled by the service |
| Control | Full control of machines and environment | Convenience, less control |
10. What is the problem with running shards on plain ubuntu-latest?
Each shard is a fresh machine, so each one must install the browsers before it can run a single test. The command for that on a CI machine is:
npx playwright install --with-deps
The first half, npx playwright install, downloads the browser binaries. The –with-deps flag adds a second job: installing the operating-system libraries those browsers need to launch, such as audio, font and codec libraries.
A developer laptop usually does not need –with-deps, because a desktop operating system already ships with those libraries. A CI runner is a minimal headless server image without them, so the browser would download fine and then fail to start. On Windows and macOS runners the flag is not the concern; it matters on Linux.
The immediate cost is repetition: with 4 shards, the same download and installation happens 4 times in parallel, on every run.
11. Give a real example where installing browsers on ubuntu-latest broke a pipeline.
When GitHub moved ubuntu-latest from Ubuntu 22.04 to 24.04, many pipelines that ran npx playwright install –with-deps started failing, even though nobody had changed a line of code or upgraded Playwright.
The failure came from the operating-system layer. Ubuntu 24.04 had renamed or upgraded several system packages, and apt could no longer find installation candidates for names such as libasound2, libicu70 and libx264-163 that the Playwright dependency installer was asking for. The Playwright browser binaries themselves were fine. It was the OS libraries underneath them that changed, and the dependency step was tied to the old package names until Playwright added support for the new release.
The lesson: the browser download is deterministic, but the OS dependency step is coupled to whatever operating system the label points at on that day. The pipeline that passed yesterday can fail today with no change on your side.
So the fix has to freeze the environment, operating system libraries and all. That is exactly what Docker does.
12. How does Docker solve the problem in this pipeline, and is it mandatory?
Docker packages an application together with its entire runtime environment, meaning the OS libraries, dependencies and configuration, into a single portable unit called an image. When the image runs, it runs inside an isolated container that behaves the same no matter what machine it sits on, because the container carries its own filesystem instead of depending on whatever the host has installed.
This solves the classic “it works on my machine” problem. Instead of hoping every machine has the right library versions, the image is built once with an exact, frozen set of dependencies, and that exact set travels everywhere it runs: a laptop, a CI runner or a server.
Microsoft publishes an official Playwright Docker image for each Playwright version. It contains the browsers and every operating-system dependency they need, frozen at build time. The job simply runs inside that image using the container key, pinned to an exact tag such as mcr.microsoft.com/playwright:v1.49.0-noble. The version should match the @playwright/test version in package.json.
- The –with-deps step disappears; the dependency layer is already baked in.
- There is no per-shard browser download; browsers are ready when the container starts.
- There is no exposure to ubuntu-latest drift, because the image tag never moves.
One last question ties the whole story together.
13. Given all this, how would you decide which approach to use for a team?
Start from the team’s situation rather than the tool.
- If the suite is small to medium and the team already pays for GitHub Actions, use shards. Add Docker once the repeated browser installs cost real minutes or the OS drift risk matters.
- If the team needs parallelism beyond the account’s concurrent-job limit, or broad browser and OS coverage without managing runners, cloud-hosted browsers on Azure are worth the extra bill.
- In both cases, measure first. Track how long the pipeline takes and how many runner-minutes it uses, then choose the option that removes the actual bottleneck.
Summary
CI runs tests on every push. On GitHub the tests run on one small machine, which becomes slow as the suite grows. You can go parallel by renting cloud browsers on Azure, or by sharding across several GitHub runners. Shards split the suite across machines and workers parallelize within each machine, and a merge job combines the results. Azure trades an extra bill for convenience and elasticity. Shards cost nothing new but must install browsers on every machine, and that install can break when ubuntu-latest moves to a new Ubuntu version. Docker freezes the environment so that cannot happen, and the final pipeline combines sharding, Docker and a merge job to deliver Azure-style parallelism on GitHub alone.
Want to go deeper than interview answers?
Our Playwright course covers everything here hands-on — real frameworks, CI/CD pipelines, and production-grade projects, not just Q&A. Explore the Playwright Course
