Automation Engineering is the backbone of modern quality assurance at scale. This chapter covers 25 essential interview questions that explore how senior QA engineers design, implement, maintain, and optimize test automation frameworks. Topics span architecture decisions, selector strategies, flakiness mitigation, CI/CD integration, cross-browser testing, and migration strategies.
A senior QA engineer must demonstrate not just the ability to write automated tests, but the engineering judgment to build sustainable, maintainable automation ecosystems that deliver fast, reliable feedback to development teams.
Q1Describe a maintainable automation architecture.#
Objective
Assess the candidate's ability to design automation frameworks that scale with team size, product complexity, and evolving requirements without becoming a maintenance burden.
Interview Answer
A maintainable automation architecture follows the layered abstraction principle: tests speak in business language, an interaction layer translates intent to actions, and infrastructure handles execution details. I structure frameworks with three distinct layers.
Layer 1 — Test Layer contains readable scenarios that express business intent without implementation details. Layer 2 — Interaction Layer encapsulates page objects, API clients, and component models. Layer 3 — Infrastructure Layer manages browser setup, reporting, retry logic, and environment configuration.
Key principles I enforce: Single Responsibility — each class has one reason to change. DRY at the right level — I extract shared behavior into fixtures and helpers but avoid premature abstraction. Composition over inheritance — I compose page objects from component fragments rather than deep inheritance trees. Configuration-driven — environment URLs, timeouts, and feature flags live in config files, not hardcoded in tests.
I also enforce strict separation between test data creation (via API or database seeding) and test execution (via UI or API assertions). This keeps tests fast and independent.
Evaluate the candidate's understanding of selector strategies that balance reliability, readability, and maintenance cost.
Interview Answer
Selector strategy is one of the most impactful decisions for test stability. I follow Playwright's recommended priority: user-facing attributes first, then semantic roles, then test IDs as a fallback.
My hierarchy is: (1) getByRole — mirrors accessibility tree, resilient to CSS changes. (2) getByLabel / getByPlaceholder — form inputs by their visible labels. (3) getByText — visible text content for buttons and links. (4) getByTestId — explicit data-testid attributes when semantic selectors aren't feasible. (5) CSS/XPath — last resort for complex dynamic content.
The key insight is that good selectors test what users see, not implementation details. If a selector breaks when a developer refactors CSS classes, it was testing the wrong thing. If it breaks when visible text changes, that's a legitimate requirement change that should surface.
I establish a team convention: developers add data-testid only when accessibility attributes don't provide a unique hook. We lint for banned selector patterns (no CSS class selectors, no XPath with positional indices).
┌─────────────────────────────────────┐
│ Need to locate an element? │
└──────────────┬──────────────────────┘
▼
┌─────────────────────────────────────┐
│ Does it have a role + accessible │──── YES ──→ getByRole()
│ name? (button, link, heading, etc.) │
└──────────────┬──────────────────────┘
│ NO
▼
┌─────────────────────────────────────┐
│ Is it a form field with a label? │──── YES ──→ getByLabel()
└──────────────┬──────────────────────┘
│ NO
▼
┌─────────────────────────────────────┐
│ Has unique, stable visible text? │──── YES ──→ getByText()
└──────────────┬──────────────────────┘
│ NO
▼
┌─────────────────────────────────────┐
│ Can you add a data-testid? │──── YES ──→ getByTestId()
└──────────────┬──────────────────────┘
│ NO
▼
┌─────────────────────────────────────┐
│ Use CSS locator (last resort) │──────────→ page.locator()
└─────────────────────────────────────┘
Code Example — Custom Selector Helper
// src/helpers/selectors.tsimport { typePage, typeLocator } from'@playwright/test';
exportclassSmartLocator {
constructor(privatereadonlypage: Page) {}
/** Locate a table row by its visible cell content */rowContaining(text: string): Locator {
returnthis.page.getByRole('row').filter({ hasText: text });
}
/** Locate form field by label, supporting nested labels */field(label: string): Locator {
returnthis.page.getByLabel(label);
}
/** Locate within a specific section */withinSection(sectionName: string): Locator {
returnthis.page.getByRole('region', { name: sectionName });
}
}
ESLint Rule — Ban Fragile Selectors
// .eslintrc.js — Custom rule to prevent CSS class selectorsmodule.exports = {
rules: {
'no-restricted-syntax': [
'error',
{
selector: 'CallExpression[callee.property.name="locator"][arguments.0.value=/^\\./]',
message: 'Avoid CSS class selectors. Use getByRole, getByLabel, or getByTestId.',
},
],
},
};
Test the candidate's understanding of synchronization patterns and why time-based waits are an anti-pattern in test automation.
Interview Answer
Hard waits (waitForTimeout, Thread.sleep) are the number one source of slow, flaky tests. They either wait too long (slow suite) or not long enough (flaky failures). I replace them with condition-based waits that resolve the instant the condition is met.
Playwright has built-in auto-waiting on actions — click(), fill(), check() all wait for actionability (visible, enabled, stable). For assertions, I use expect with Playwright's auto-retry — it polls until the condition passes or timeout expires. For custom conditions, I use waitForFunction, waitForResponse, or waitForURL.
My strategy: (1) Leverage built-in auto-wait — Playwright waits for actionability before every action. (2) Use web-first assertions — expect(locator).toBeVisible() retries automatically. (3) Wait for network — waitForResponse when tests depend on API calls completing. (4) Wait for URL changes — waitForURL for navigation-dependent flows. (5) Custom polling — expect.poll() for non-DOM conditions.
Code Example — Playwright TypeScript
// ❌ BAD: Hard waits — arbitrary, slow, still flakyawait page.click('#submit');
await page.waitForTimeout(3000); // Hope the API responds in 3sawaitexpect(page.locator('.success')).toBeVisible();
// ✅ GOOD: Wait for specific network responseawait page.getByRole('button', { name: 'Submit' }).click();
const response = await page.waitForResponse(
resp => resp.url().includes('/api/orders') && resp.status() === 201
);
awaitexpect(page.getByText('Order confirmed')).toBeVisible();
// ✅ GOOD: Wait for URL change after navigationawait page.getByRole('link', { name: 'Dashboard' }).click();
await page.waitForURL('**/dashboard');
// ✅ GOOD: Poll a custom condition (non-DOM)await expect.poll(async () => {
const response = await page.request.get('/api/jobs/123');
return response.json().then(data => data.status);
}, { timeout: 30_000, intervals: [1000, 2000, 5000] }).toBe('completed');
// ✅ GOOD: Wait for loading state to disappearawaitexpect(page.getByTestId('loading-spinner')).toBeHidden();
awaitexpect(page.getByRole('table')).toBeVisible();
// ✅ GOOD: waitForFunction for complex DOM conditionsawait page.waitForFunction(() => {
const rows = document.querySelectorAll('table tbody tr');
return rows.length >= 10;
});
Code Example — REST Assured Java (Polling Pattern)
// ❌ BAD: Thread.sleep in API tests@TestvoidshouldProcessOrder() {
postOrder(orderPayload);
Thread.sleep(5000); // Hoping async processing completesResponseresponse= getOrder(orderId);
assertThat(response.jsonPath().getString("status")).isEqualTo("processed");
}
// ✅ GOOD: Awaitility for async API conditions@TestvoidshouldProcessOrderAsync() {
postOrder(orderPayload);
await().atMost(Duration.ofSeconds(30))
.pollInterval(Duration.ofSeconds(2))
.untilAsserted(() -> {
Responseresponse= getOrder(orderId);
assertThat(response.jsonPath().getString("status"))
.isEqualTo("processed");
});
}
Evaluate the candidate's experience diagnosing and preventing test flakiness — one of the most damaging problems in test automation.
Interview Answer
Flaky tests are tests that pass and fail non-deterministically without code changes. They erode trust in the suite and eventually get ignored. I categorize root causes into five buckets:
1. Timing and synchronization — Race conditions between test actions and application state. The app hasn't finished rendering, an animation is in progress, or an API response hasn't arrived.
2. Test isolation failures — Tests share state (database records, browser cookies, global variables). Order-dependent tests pass in sequence but fail in parallel or shuffled.
3. Environmental instability — Network latency variations, DNS resolution, third-party service availability, CI resource contention (CPU/memory causing timeouts).
4. Non-deterministic data — Tests that depend on current time, random values, sort order of equal elements, or data created by other tests.
5. Application bugs masked as test issues — Genuine race conditions in the product that only surface under specific timing. These are valuable signals, not test problems.
My approach to each: For timing, use condition-based waits and Playwright's auto-waiting. For isolation, ensure each test creates its own data and runs in a fresh context. For environment, use retry mechanisms and realistic timeouts. For data, control all inputs explicitly.
// ❌ FLAKY: Race condition — element may not be rendered yettest('shows user count', async ({ page }) => {
await page.goto('/admin');
const count = await page.locator('.user-count').textContent();
expect(Number(count)).toBeGreaterThan(0);
});
// ✅ STABLE: Web-first assertion with auto-retrytest('shows user count', async ({ page }) => {
await page.goto('/admin');
awaitexpect(page.getByTestId('user-count')).not.toHaveText('0');
});
// ❌ FLAKY: Depends on element order in DOMtest('first item is Apple', async ({ page }) => {
await page.goto('/products');
const firstItem = await page.locator('.product-item').first();
awaitexpect(firstItem).toHaveText('Apple');
});
// ✅ STABLE: Asserts content exists without assuming ordertest('Apple appears in product list', async ({ page }) => {
await page.goto('/products');
awaitexpect(page.getByRole('list')).toContainText('Apple');
});
// ❌ FLAKY: Test depends on shared datatest('delete last user', async ({ page }) => {
await page.goto('/users');
await page.getByRole('row').last().getByRole('button', { name: 'Delete' }).click();
// Fails if another test already deleted users
});
// ✅ STABLE: Test creates its own datatest('can delete a user', async ({ page, request }) => {
// Arrange: Create test-specific user via APIconst user = await request.post('/api/users', {
data: { name: 'DeleteMe', email: `del-${Date.now()}@test.com` }
});
const userId = (await user.json()).id;
await page.goto('/users');
await page.getByRole('row', { name: 'DeleteMe' })
.getByRole('button', { name: 'Delete' }).click();
awaitexpect(page.getByRole('row', { name: 'DeleteMe' })).toBeHidden();
});
CI Configuration — Retry Strategy
# .github/workflows/tests.yml-name:RunPlaywrightTestsrun:npxplaywrighttest--retries=2env:CI:true# playwright.config.ts — Different retry per environmentretries:process.env.CI?2 :0,
Common Mistakes to Avoid
Quarantining without investigation — Muting flaky tests hides real problems
Adding retries as a permanent fix — Retries are a safety net, not a solution
Blaming the framework — Most flakiness comes from test design, not tools
Ignoring CI resource limits — Parallel tests fighting for CPU cause timeouts
Not tracking flakiness metrics — Can't improve what you don't measure
Follow-up Questions
How do you distinguish a flaky test from an intermittent product bug?
What flakiness rate is acceptable for a CI suite?
How do you prioritize which flaky tests to fix first?
Assess the candidate's systematic debugging approach for non-deterministic test failures.
Interview Answer
Diagnosing flakiness requires a systematic approach because the root cause isn't obvious from a single failure. My process has five steps:
Step 1: Reproduce locally — Run the test in a loop (--repeat-each=50) to confirm it's genuinely flaky and estimate failure rate. If it only fails in CI, the environment is a factor.
Step 2: Analyze artifacts — Check trace files, screenshots, and video from the failure. Playwright's trace viewer shows exact timeline of actions, network calls, and DOM snapshots at each step.
Step 3: Check timing — Look for race conditions. Is the failure always at the same step? Does the trace show the element wasn't ready? Was a network call still pending?
Step 4: Check isolation — Run the test alone vs. in suite. If it only fails with other tests, there's shared state. Use --shard to narrow which tests interfere.
Step 5: Check environment — Compare CI vs. local: CPU/memory, network speed, browser version, OS, screen resolution, timezone.
I also use flakiness dashboards that track pass/fail history per test, making patterns visible (fails only on Mondays → data refresh, fails after 5pm → certificate rotation).
Code Example — Playwright TypeScript
// Step 1: Reproduce with repetition// CLI: npx playwright test login.spec.ts --repeat-each=50 --workers=1// Step 2: Enable trace for debugging// playwright.config.tsuse: {
trace: 'on', // Capture trace for every run during diagnosisvideo: 'on',
screenshot: 'on',
}
// Step 3: Add diagnostic logging to identify timingtest('flaky order submission', async ({ page }) => {
await page.goto('/checkout');
// Add event listeners to understand timing
page.on('response', response => {
if (response.url().includes('/api/orders')) {
console.log(`[${Date.now()}] API response: ${response.status()}`);
}
});
await page.getByRole('button', { name: 'Place order' }).click();
// Capture DOM state at assertion timeconst html = await page.content();
console.log('DOM at assertion:', html.substring(0, 500));
awaitexpect(page.getByText('Order confirmed')).toBeVisible();
});
// Step 4: Isolation check — tag and run subsets// npx playwright test --grep @checkout --workers=1// npx playwright test --grep @checkout --workers=4// Step 5: Custom reporter for flakiness trackingimporttype { Reporter, TestCase, TestResult } from'@playwright/test/reporter';
classFlakinessReporterimplementsReporter {
privateresults: Map<string, { pass: number; fail: number }> = newMap();
onTestEnd(test: TestCase, result: TestResult) {
const key = test.titlePath().join(' > ');
const current = this.results.get(key) ?? { pass: 0, fail: 0 };
if (result.status === 'passed') current.pass++;
else current.fail++;
this.results.set(key, current);
}
onEnd() {
for (const [name, stats] ofthis.results) {
const total = stats.pass + stats.fail;
const flakyRate = (stats.fail / total * 100).toFixed(1);
if (stats.fail > 0 && stats.pass > 0) {
console.log(`FLAKY [${flakyRate}%]: ${name}`);
}
}
}
}
exportdefaultFlakinessReporter;
Diagnosis Decision Tree
Test failed in CI
│
▼
Can you reproduce locally with --repeat-each=50?
│
YES ─┤── NO ──────────────────────────────────┐
│ ▼
▼ Compare CI environment:
Review trace file - CPU/memory constraints?
│ - Different browser version?
▼ - Network latency?
Failure at which step? - Screen resolution?
│
┌────┼──────────────┐
▼ ▼ ▼
Action Assertion Navigation
fails fails times out
│ │ │
▼ ▼ ▼
Element Stale data Slow API
not ready or race or redirect
│ │ │
▼ ▼ ▼
Fix wait Fix assert waitForURL
strategy timing or response
Common Mistakes to Avoid
Skipping reproduction — Assuming cause without evidence leads to wrong fixes
Only checking the failed step — Root cause is often earlier in the test
Not using trace viewer — Most powerful diagnostic tool available
Fixing symptoms — Adding a retry without understanding why it failed
Not checking test interdependence — Flakiness often comes from test pollution
Follow-up Questions
How long do you spend diagnosing before quarantining a flaky test?
How do you handle a test that's flaky only in one CI environment?
What's your threshold for retries vs. fixing the root cause?
How do you communicate flakiness trends to the team?
Evaluate the candidate's strategy for test data creation, isolation, and cleanup to ensure reliable, repeatable test execution.
Interview Answer
Test data management is critical for parallel, repeatable, environment-independent tests. My strategy has four pillars:
1. API-first creation — Tests create their own data via API calls before exercising the UI. This is faster than UI setup and more reliable. Each test is self-contained.
2. Unique data per test — Every test generates unique identifiers (timestamps, UUIDs) to prevent collision during parallel execution. No test assumes pre-existing data.
3. Factory pattern — Builder/factory classes produce valid test entities with sensible defaults, allowing tests to override only fields they care about.
4. Cleanup strategy — For isolated environments, I rely on ephemeral databases (Docker containers per test run). For shared environments, tests clean up after themselves or use short-lived data with TTL.
I avoid shared test fixtures (like a "golden" user that all tests use) because they create hidden dependencies and break under parallel execution.
┌─────────────────┬────────────────────┬────────────────────────┐
│ Strategy │ Pros │ Cons │
├─────────────────┼────────────────────┼────────────────────────┤
│ API seeding │ Fast, reliable │ Requires API access │
│ DB seeding │ Full control │ Couples to schema │
│ UI creation │ Tests real flow │ Slow, fragile │
│ Shared fixtures │ Simple setup │ Not parallelizable │
│ Docker per run │ Full isolation │ Startup time cost │
│ Snapshot/restore│ Consistent state │ Complex infrastructure │
└─────────────────┴────────────────────┴────────────────────────┘
Common Mistakes to Avoid
Shared mutable test data — One test's cleanup breaks another test's assumptions
Database dumps as fixtures — Drift from real schema, hard to maintain
Hardcoded IDs — Break across environments and parallel runs
No cleanup strategy — Test data accumulates, slowing environments
Relying on data order — Database query order isn't guaranteed without ORDER BY
Follow-up Questions
How do you handle test data for performance/load tests?
How do you seed data for visual regression tests that need consistent screenshots?
What's your approach when the API doesn't expose all needed data creation endpoints?
How do you manage test data across microservices?
Q7How do you isolate tests for parallel execution?#
Objective
Assess the candidate's ability to design tests that run concurrently without interfering with each other.
Interview Answer
Parallel execution is essential for fast feedback, but it demands strict test isolation. My isolation strategy operates at four levels:
Browser context isolation — Each Playwright test gets a fresh browser context (cookies, localStorage, sessions are independent). This is the default behavior and handles most UI state isolation.
Data isolation — Each test creates unique data using identifiers like UUIDs or timestamps. No test queries "all records" — it only interacts with its own data.
Account isolation — Tests that modify user settings get their own user account. Tests that only read can share read-only accounts if they don't mutate state.
Service isolation — For tests hitting shared backend services, I use tenant isolation or namespace prefixes to prevent cross-test contamination.
I configure Playwright with fullyParallel: true and verify isolation by running the suite with --workers=8 and --repeat-each=3. If any test fails only during parallel execution, it has an isolation bug.
Code Example — Playwright TypeScript
// playwright.config.ts — Parallel configurationimport { defineConfig } from'@playwright/test';
exportdefaultdefineConfig({
fullyParallel: true,
workers: process.env.CI ? 4 : undefined,
use: {
// Each test gets fresh context (default behavior)storageState: undefined,
},
});
// src/fixtures/isolated.ts — Isolated fixture per testimport { test as base } from'@playwright/test';
exportconst test = base.extend<{
isolatedAccount: { email: string; password: string; token: string };
}>({
isolatedAccount: async ({ request }, use) => {
// Create unique account for this testconst email = `parallel-${crypto.randomUUID()}@test.local`;
const password = 'SecurePass123!';
const signupResponse = await request.post('/api/auth/signup', {
data: { email, password, name: 'Parallel Test User' },
});
const { token } = await signupResponse.json();
awaituse({ email, password, token });
// Cleanup: delete account after testawait request.delete('/api/auth/account', {
headers: { Authorization: `Bearer ${token}` },
});
},
});
// tests/e2e/settings.spec.ts — Fully isolated testimport { test } from'../../src/fixtures/isolated';
test('user can change display name', async ({ page, isolatedAccount }) => {
// This test has its own account — safe for parallel executionawait page.goto('/login');
await page.getByLabel('Email').fill(isolatedAccount.email);
await page.getByLabel('Password').fill(isolatedAccount.password);
await page.getByRole('button', { name: 'Sign in' }).click();
await page.goto('/settings');
await page.getByLabel('Display name').fill('New Name');
await page.getByRole('button', { name: 'Save' }).click();
awaitexpect(page.getByText('Settings saved')).toBeVisible();
});
Code Example — REST Assured Java (Parallel Isolation)
Test the candidate's understanding of Playwright's fixture system for managing test setup, teardown, and shared resources.
Interview Answer
Fixtures in Playwright are a powerful dependency injection system. They provide two key benefits: automatic lifecycle management (setup before test, teardown after) and composability (fixtures can depend on other fixtures).
I use fixtures for: (1) Authenticated state — Login once via API, reuse storage state. (2) Test data — Create and clean up entities per test. (3) Page objects — Instantiate and provide pre-configured page objects. (4) Custom contexts — Browser contexts with specific settings (viewport, locale, permissions).
Fixtures replace beforeEach/afterEach hooks with advantages: they're lazy (only created when the test uses them), they compose naturally, and they make dependencies explicit in the test signature.
I organize fixtures in layers: base fixtures (auth, data factories), domain fixtures (specific to feature areas), and test-specific overrides.
Evaluate the candidate's approach to collecting diagnostic information when tests fail, enabling rapid root cause analysis.
Interview Answer
Artifacts are the forensic evidence that makes failed tests diagnosable without re-running them. I capture four types: screenshots (visual state at failure), traces (complete timeline with DOM snapshots, network, console), videos (full test execution recording), and logs (browser console, network HAR files).
My strategy is progressive: capture lightweight artifacts always (screenshots on failure), medium artifacts on first retry (traces), and heavy artifacts on-demand (video for investigation mode). This balances storage costs with diagnostic value.
I configure artifact retention in CI to keep failures for 7 days and quarantine artifacts for 30 days. Artifacts are attached to test reports so developers can click directly from a failed test to its trace file.
The most powerful artifact is Playwright's trace — it provides a complete replayable timeline including DOM snapshots at each step, network waterfall, console logs, and action timing.
Assess the candidate's approach to validating API contracts between services, ensuring interface compatibility without full integration testing.
Interview Answer
Contract testing verifies that API consumers and providers agree on the interface — request/response schemas, status codes, headers — without requiring both to be running simultaneously. This catches breaking changes before they reach integration environments.
I implement contracts at two levels: Consumer-driven contracts (CDC) where consumers define their expectations and providers verify they meet them, and Schema validation where API responses are validated against OpenAPI/JSON Schema specifications.
My preferred approach uses Pact for microservice CDC testing and schema validation within Playwright/REST Assured tests for simpler scenarios. The key insight: contract tests answer "will these services work together?" without the cost of running full integration tests.
I integrate contracts into CI so that a provider build fails if it would break a consumer, and a consumer build fails if it expects something the provider doesn't offer.
Code Example — Playwright TypeScript (Schema Validation)
Testing business logic in contracts — Contracts verify shape, not behavior
Tight coupling to response values — Check types and structure, not specific data
Skipping error response contracts — Error formats are part of the API contract
No versioning strategy — Breaking changes need a migration path
Not testing headers — Content-Type, pagination headers are contractual
Follow-up Questions
How do you handle backward-compatible vs. breaking contract changes?
When do you choose Pact CDC vs. schema validation?
How do you test GraphQL contracts?
How do you contract-test event-driven (async) interfaces?
Q11How do you use mocks and service virtualization?#
Objective
Evaluate the candidate's understanding of when and how to isolate systems under test from external dependencies.
Interview Answer
Mocks and service virtualization let us test components in isolation by replacing real dependencies with controlled substitutes. I use them in three contexts:
1. Network-level mocking in UI tests — Playwright's route() API intercepts HTTP requests, letting me control responses without touching the backend. This is ideal for testing error states, edge cases, and offline scenarios.
2. Service virtualization for integration environments — Tools like WireMock or MockServer simulate third-party APIs (payment gateways, email services) with realistic response patterns including latency and error rates.
3. API mocking during development — When the backend isn't ready, mocks let frontend and test development proceed in parallel.
The key decision: mock at the narrowest boundary possible. For unit tests, mock function calls. For integration tests, mock at the network boundary. For E2E tests, prefer real services but mock external third parties you don't own.
I follow the rule: own it? Test it real. Don't own it? Mock it.
Code Example — Playwright TypeScript (Network Mocking)
┌────────────────────────────────────────────────────────┐
│ WHEN TO MOCK vs. USE REAL SERVICE │
├─────────────────────────┬──────────────────────────────┤
│ MOCK │ REAL │
├─────────────────────────┼──────────────────────────────┤
│ Third-party APIs │ Your own services │
│ Payment gateways │ Your database │
│ Email/SMS providers │ Your message queues │
│ Error/edge cases │ Happy path flows │
│ Rate-limited services │ Services in your test env │
│ Slow external calls │ Fast internal calls │
│ Unavailable services │ Stable, available services │
└─────────────────────────┴──────────────────────────────┘
Common Mistakes to Avoid
Mocking your own services in E2E — Defeats the purpose of integration testing
Stale mocks — Mock responses drift from real API over time
Over-mocking — Testing mock behavior instead of real application behavior
Not verifying mock interactions — Mock was set up but never called (test passes vacuously)
Complex conditional mocks — If mocking logic is complex, you're testing the mock
Follow-up Questions
How do you keep mocks in sync with real API changes?
When would you use page.route() vs. a mock server?
How do you mock WebSocket connections?
What's the difference between mocks, stubs, and fakes?
Test the candidate's strategic thinking about testing at different levels of the stack to maximize coverage while minimizing execution time.
Interview Answer
The testing pyramid guides my coverage decisions: most tests at the API level, fewer at the UI level. But I apply this pragmatically based on risk and value.
UI tests for: User-facing workflows that exercise frontend logic (form validation, navigation, responsive behavior, accessibility), visual correctness, and critical end-to-end happy paths that validate the full stack works together.
API tests for: Business logic validation, data transformation rules, authorization checks, error handling, performance baselines, and combinatorial input validation where UI would be prohibitively slow.
My ratio is typically 70% API / 20% UI / 10% unit for backend-heavy applications, shifting to 50% API / 40% UI / 10% unit for frontend-heavy applications.
The key principle: test at the lowest level that gives you confidence. If you can verify a discount calculation via API in 50ms, don't test it through the UI in 5 seconds. But if the bug would be "the button doesn't appear for free-tier users," only a UI test catches that.
Code Example — Playwright TypeScript (Strategic Coverage)
// ✅ API TEST: Validates business rules (fast, many scenarios)// tests/api/discount.spec.ts
test.describe('Discount Calculation API', () => {
const scenarios = [
{ items: 1, total: 100, expectedDiscount: 0 },
{ items: 5, total: 500, expectedDiscount: 25 }, // 5% bulk
{ items: 10, total: 1000, expectedDiscount: 100 }, // 10% bulk
{ items: 10, total: 5000, expectedDiscount: 750 }, // 15% VIP
];
for (const { items, total, expectedDiscount } of scenarios) {
test(`${items} items totaling $${total} gets $${expectedDiscount} discount`, async ({ request }) => {
const response = await request.post('/api/v1/cart/calculate', {
data: { itemCount: items, subtotal: total },
});
const body = await response.json();
expect(body.discount).toBe(expectedDiscount);
});
}
});
// ✅ UI TEST: Validates user experience (slower, fewer scenarios)// tests/e2e/checkout-discount.spec.tstest('discount badge appears when bulk threshold is met', async ({ page, testUser }) => {
// Only ONE UI test for the discount feature — verifies display, not calculationawait page.goto('/cart');
// Add items to reach bulk discount thresholdfor (let i = 0; i < 5; i++) {
await page.getByRole('button', { name: 'Add item' }).click();
}
awaitexpect(page.getByTestId('discount-badge')).toBeVisible();
awaitexpect(page.getByTestId('discount-badge')).toContainText('5% bulk discount applied');
});
Coverage Strategy Matrix
┌─────────────────────┬─────────────┬────────────────┬───────────────┐
│ What to Validate │ Test Level │ Speed │ # of Tests │
├─────────────────────┼─────────────┼────────────────┼───────────────┤
│ Business rules │ API │ ~50ms each │ Many (20+) │
│ Input validation │ API │ ~50ms each │ Many (10+) │
│ Authorization │ API │ ~100ms each │ Per role (5+) │
│ Error responses │ API │ ~50ms each │ Per error │
│ UI renders correctly│ UI │ ~3s each │ Few (3-5) │
│ User workflows │ UI │ ~10s each │ Critical only │
│ Accessibility │ UI │ ~5s each │ Per page │
│ Visual regression │ UI │ ~5s each │ Per component │
│ Cross-browser │ UI │ ~10s × browsers│ Smoke subset │
└─────────────────────┴─────────────┴────────────────┴───────────────┘
Decision Flowchart
┌─────────────────────────────────┐
│ New feature needs test coverage │
└───────────────┬─────────────────┘
▼
┌─────────────────────────────────┐
│ Does it involve frontend-only │
│ logic? (rendering, animations, │── YES ──→ UI Test
│ responsive behavior) │
└───────────────┬─────────────────┘
│ NO
▼
┌─────────────────────────────────┐
│ Is it a business rule that │
│ can be validated via API? │── YES ──→ API Test
└───────────────┬─────────────────┘
│ NO
▼
┌─────────────────────────────────┐
│ Is it a critical user journey │
│ spanning multiple pages? │── YES ──→ UI E2E Test
└───────────────┬─────────────────┘
│ NO
▼
┌─────────────────────────────────┐
│ Can you verify with unit test? │── YES ──→ Unit Test
└─────────────────────────────────┘
Common Mistakes to Avoid
Testing everything through UI — Slow, flaky, expensive to maintain
No UI tests at all — Misses rendering bugs, accessibility issues, UX problems
Duplicating coverage across levels — API test validates math, UI test re-validates same math
Using UI tests for data setup — Create data via API, verify via UI
Ignoring the frontend is an application — Complex SPAs need their own testing strategy
Follow-up Questions
How does your ratio change for a mobile application?
When would you increase UI coverage beyond the typical ratio?
How do you track coverage gaps between API and UI layers?
How do you handle features that only exist in the UI (no API)?
The override process requires: (1) A ticket for the known issue, (2) Risk assessment by the on-call engineer, (3) A revert plan if the issue impacts production.
Evaluate the candidate's approach to communicating test results to different stakeholders in actionable formats.
Interview Answer
Reporting serves different audiences with different needs. I design multi-layered reporting:
For developers (immediate): Inline CI annotations showing exactly which line/test failed, with trace links. GitHub Actions annotations or Slack notifications with direct links to failure artifacts.
For QA leads (daily): Dashboard showing suite health — pass rate trends, flakiness rate, execution time trends, new failures vs. known issues.
For management (weekly): High-level metrics — automation coverage growth, time saved, defect escape rate, mean time to green.
Key principles: (1) Link to evidence — every failure links to its trace/screenshot. (2) Trend over snapshot — a single run's results are less informative than trends. (3) Signal, not noise — suppress known flaky tests from default view. (4) Actionable — every failure report includes suggested next steps.
Code Example — Playwright TypeScript (Custom Reporter)
Report without action — Reports that nobody reads or acts on
Too much detail for executives — They need trends, not stack traces
No links to artifacts — "Test failed" without evidence is useless
Counting tests, not coverage — 500 tests could cover 20% of features
Not tracking flaky vs. real failures — Conflating the two destroys signal
Follow-up Questions
How do you prevent alert fatigue from test notifications?
What reporting cadence works for different team sizes?
How do you report on tests that pass but are slow?
How do you make reports useful during incident investigation?
Q16How do you organize page objects or screen models?#
Objective
Assess the candidate's approach to structuring page abstractions that remain maintainable as the application grows.
Interview Answer
Page objects encapsulate UI interactions behind a business-language API. My organization principles:
1. One file per logical page — /login, /dashboard, /settings each get their own page object.
2. Extract reusable components — Header, navigation, modals, data tables that appear on multiple pages become shared components.
3. Composition over inheritance — Pages compose components rather than inheriting from base classes. A CheckoutPage uses a CartWidget and PaymentForm component.
4. No assertions in page objects — Page objects expose state (getters, locators) but tests make assertions. This keeps page objects reusable across different test scenarios.
5. Return types guide navigation — Methods that navigate to a new page return the new page object, creating fluent chains.
Evaluate the candidate's understanding of secure credential management in test automation environments.
Interview Answer
Secrets in automation include API keys, test user passwords, database credentials, and service tokens. My approach follows the principle: never in code, always from environment.
Strategy layers:
Environment variables in CI — Secrets stored in GitHub Actions secrets, Jenkins credentials, or AWS Secrets Manager. Injected at runtime, never checked into code.
Local development — .env.local files (git-ignored) or a secrets manager CLI for local runs.
Rotation — Test credentials use short-lived tokens where possible. Long-lived secrets rotate on a schedule.
Least privilege — Test accounts have minimum permissions needed. Automation service accounts are separate from human accounts.
Audit trail — All secret access is logged. Secrets are scoped to specific pipelines/environments.
The key rule: if you grep -r "password" in the repo, you find zero real credentials. Only placeholder names and references to environment variables.
Assess the candidate's cross-browser testing strategy that balances coverage with execution cost.
Interview Answer
Cross-browser testing validates that the application works consistently across different rendering engines. My strategy is risk-based: not every test needs every browser.
Tiered approach:
Chromium only — Full suite runs on Chromium (fastest, most features). This is the primary feedback loop.
Multi-browser smoke — Critical user journeys (login, checkout, search) run on Firefox and WebKit. This catches rendering engine differences.
Full cross-browser — Scheduled nightly run of the complete suite across all browsers. Catches edge cases without slowing PRs.
The reason: most bugs are logic bugs (caught by any browser). Browser-specific bugs are typically CSS rendering, font handling, or API differences in Web APIs — and they appear in critical flows if they exist.
I also test mobile viewports separately from mobile browsers. Responsive design bugs show up at specific breakpoints regardless of browser.
┌──────────────────┬───────────┬─────────┬────────┬──────────┐
│ Test Type │ Chromium │ Firefox │ WebKit │ Mobile │
├──────────────────┼───────────┼─────────┼────────┼──────────┤
│ Full E2E Suite │ Every PR │ Nightly │ Nightly│ Nightly │
│ Smoke Tests │ Every PR │ Every PR│ Every PR│ Every PR │
│ Visual Regress. │ Every PR │ Weekly │ Weekly │ Every PR │
│ Accessibility │ Every PR │ — │ — │ Every PR │
│ Performance │ Every PR │ — │ — │ Weekly │
└──────────────────┴───────────┴─────────┴────────┴──────────┘
Common Mistakes to Avoid
Running everything on all browsers — Multiplies execution time by 3-5x
Only testing desktop — Mobile traffic often exceeds desktop
Ignoring Safari/WebKit — Most browser-specific bugs appear here
Testing mobile only with viewports — Touch events and device APIs differ
Not pinning browser versions — Updates can introduce new failures
Follow-up Questions
How do you handle browser-specific workarounds without polluting tests?
When do you use real devices vs. emulation?
How do you handle features not supported in all browsers?
How do you debug a browser-specific failure?
Q19How do you test performance without making UI tests slow?#
Objective
Evaluate the candidate's ability to integrate lightweight performance checks into functional test suites without compromising feedback speed.
Interview Answer
Performance testing and functional testing serve different purposes but can share infrastructure. My approach: embed lightweight performance assertions in functional tests and run dedicated performance tests separately.
In functional tests, I measure but don't load-test:
Page load timing — Assert that navigation completes within budget (e.g., < 3s).
API response time — Assert individual API calls respond within SLA.
Core Web Vitals — Capture LCP, FID, CLS metrics during normal test execution.
Resource budgets — Assert JS bundle size, number of network requests.
Separate performance tests (scheduled, not blocking PRs):
k6 or Artillery for load/stress testing
Lighthouse CI for performance scoring
Database query profiling under load
The key principle: functional tests detect regressions by comparing against baselines. They don't simulate load — that's a different test type with different infrastructure.
Evaluate the candidate's ability to quantify the business value of test automation investments.
Interview Answer
Automation ROI answers: "Is our investment in automation returning more value than it costs?" I measure across four dimensions:
1. Time savings — Manual testing time replaced by automation. Formula: (manual_time_per_cycle × cycles_per_month) - (automation_run_time + maintenance_time).
2. Defect economics — Bugs caught in CI vs. bugs caught in production. A bug caught in CI costs ~$100 to fix; in production, $1000-$10000. Track: defects found by automation, defects that escaped to production.
3. Velocity impact — Deployment frequency and lead time improvement since automation was introduced. If we deploy 3× more often with the same team, automation enabled that.
4. Maintenance cost — Time spent fixing, updating, and maintaining the automation suite. If maintenance exceeds 40% of automation team time, ROI is decreasing.
The key insight: ROI isn't just "tests passing." It's about confidence to ship faster. If the team deploys daily instead of weekly because automation provides confidence, that's the real value.
BRITTLE ◄──────────────────────────────────────► RESILIENT
Exact text Contains text Regex pattern
match match match
Exact count Range check Non-empty check
Full object Partial match Schema validation
equality (toMatchObject) (type checking)
DOM structure Semantic locator Role-based
(CSS selectors) (getByTestId) (getByRole)
Snapshot Key field Behavioral
comparison assertions assertions
Common Mistakes to Avoid
toEqual on full API responses — Breaks when any field is added/changed
Exact timestamp assertions — Time-dependent, fails across timezones
Asserting sort order without ORDER BY — Database returns are non-deterministic
Snapshot tests for dynamic content — Constant snapshot updates signal brittleness
Checking internal state — Assert user-visible outcomes, not React state
Follow-up Questions
When is an exact assertion appropriate?
How do you balance resilience with specificity?
How do you decide between toContainText and toHaveText?
How do you handle assertions on sorted data?
Q22How do you test eventual consistency in automation?#
Objective
Assess the candidate's approach to testing distributed systems where state changes are not immediately visible.
Interview Answer
Eventual consistency means that after a write, different components may temporarily show different states before converging. This is common in microservices, event-driven architectures, and systems with caches or read replicas.
Testing strategy:
Poll with timeout — After triggering an action, poll the expected endpoint until the state converges or timeout expires. Never use a fixed sleep.
Assert convergence, not timing — The test should verify the end state is correct, not how quickly it arrives. Set generous timeouts with short poll intervals.
Test the propagation guarantee — Verify that state DOES eventually propagate. If it doesn't within SLA, that's a real bug.
Test intermediate states — Some systems expose intermediate states (pending → processing → complete). Verify the state machine progression.
Idempotency verification — In eventually consistent systems, retries are common. Verify that duplicate events don't cause duplicate side effects.
Code Example — Playwright TypeScript
// tests/e2e/eventual-consistency.spec.tsimport { test, expect } from'@playwright/test';
test('order status updates eventually appear in dashboard', async ({ page, request }) => {
// Trigger action via API (writes to primary)const orderResponse = await request.post('/api/v1/orders', {
data: { items: [{ sku: 'WIDGET-001', quantity: 2 }] },
});
const { id: orderId } = await orderResponse.json();
// Poll until the read model catches upawait expect.poll(async () => {
const response = await request.get(`/api/v1/orders/${orderId}`);
const body = await response.json();
return body.status;
}, {
message: 'Order should eventually reach "confirmed" status',
timeout: 30_000,
intervals: [500, 1000, 2000, 5000],
}).toBe('confirmed');
// Now verify UI shows the updated stateawait page.goto('/orders');
awaitexpect(
page.getByRole('row', { name: newRegExp(orderId) })
.getByText('Confirmed')
).toBeVisible({ timeout: 10_000 });
});
test('search index updates after product creation', async ({ page, request }) => {
// Create product (writes to database)const product = await request.post('/api/v1/products', {
data: { name: `SearchTest-${Date.now()}`, category: 'widgets' },
});
const { name: productName } = await product.json();
// Search index is eventually consistent — poll until product appearsawait expect.poll(async () => {
const searchResult = await request.get(`/api/v1/search?q=${productName}`);
const body = await searchResult.json();
return body.results.length;
}, {
message: `Product "${productName}" should appear in search results`,
timeout: 60_000,
intervals: [1000, 2000, 5000],
}).toBeGreaterThan(0);
});
test('notification appears after async event processing', async ({ page }) => {
await page.goto('/dashboard');
// Trigger an action that generates async notificationawait page.getByRole('button', { name: 'Request report' }).click();
// Report generation is async — notification appears when doneawaitexpect(
page.getByRole('alert').filter({ hasText: 'Report ready' })
).toBeVisible({ timeout: 60_000 });
});
Code Example — REST Assured Java (Awaitility)
// Testing eventual consistency with Awaitility@Test@DisplayName("Event propagates to read model within SLA")voideventPropagatesWithinSLA() {
// Write: Create order (command side)StringorderId= given().spec(apiSpec())
.body(OrderFactory.defaultOrder())
.when()
.post("/api/v1/orders")
.then()
.statusCode(202) // Accepted (async processing)
.extract().jsonPath().getString("id");
// Read: Poll until read model is updated
await()
.atMost(Duration.ofSeconds(30))
.pollInterval(Duration.ofSeconds(1))
.pollDelay(Duration.ofMillis(500))
.untilAsserted(() -> {
given().spec(apiSpec())
.when()
.get("/api/v1/orders/" + orderId)
.then()
.statusCode(200)
.body("status", equalTo("confirmed"))
.body("confirmedAt", notNullValue());
});
}
@Test@DisplayName("Duplicate events are handled idempotently")voidduplicateEventsAreIdempotent() {
StringorderId= createOrder();
// Simulate duplicate event (payment confirmed twice)
given().spec(apiSpec())
.body(Map.of("orderId", orderId, "event", "payment_confirmed"))
.post("/api/v1/events")
.then().statusCode(200);
given().spec(apiSpec())
.body(Map.of("orderId", orderId, "event", "payment_confirmed"))
.post("/api/v1/events")
.then().statusCode(200);
// Verify only one charge occurred
await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> {
given().spec(apiSpec())
.get("/api/v1/orders/" + orderId + "/payments")
.then()
.body("charges", hasSize(1)); // Not 2!
});
}
Eventual Consistency Testing Pattern
┌──────────────────────────────────────────────────────────┐
│ EVENTUAL CONSISTENCY TEST PATTERN │
│ │
│ 1. TRIGGER │
│ └── POST /api/orders (returns 202 Accepted) │
│ │
│ 2. POLL WITH BACKOFF │
│ ├── Wait 500ms → GET /api/orders/{id} → "pending" │
│ ├── Wait 1s → GET /api/orders/{id} → "processing" │
│ ├── Wait 2s → GET /api/orders/{id} → "confirmed" │
│ └── ✅ PASS: Final state reached within timeout │
│ │
│ 3. TIMEOUT FAILURE │
│ └── After 30s → ❌ FAIL: State never converged │
│ (This indicates a real bug, not a flaky test) │
│ │
└──────────────────────────────────────────────────────────┘
Common Mistakes to Avoid
Fixed sleep instead of polling — Thread.sleep(10000) is fragile and slow
Timeout too short — Must exceed worst-case propagation time
No poll interval backoff — Hammering the API adds load; use increasing intervals
Asserting timing — "It should complete in exactly 3 seconds" is not the contract
Ignoring partial failure — What if only some replicas are updated?
Follow-up Questions
How do you set appropriate timeouts for eventually consistent systems?
How do you test systems with minutes-long propagation delays?
How do you distinguish slow propagation from a stuck process?
How do you test consistency across multiple microservices?
Evaluate the candidate's code review standards specific to test automation — what makes a good test PR vs. a risky one.
Interview Answer
Reviewing automation PRs requires a different lens than application code. I evaluate across five dimensions:
1. Readability — Can someone unfamiliar with the test understand what it validates and why? Test names should be sentences. Steps should read like user actions, not implementation details.
2. Independence — Does this test depend on other tests running first? Does it create its own data? Can it run in parallel?
3. Determinism — Are there race conditions? Hard waits? Assumptions about element order? Dynamic content assertions without patterns?
4. Maintainability — Does it reuse existing page objects and fixtures? Does it introduce duplication that should be extracted? Is the abstraction level consistent?
5. Coverage value — Does this test add unique coverage or duplicate existing tests at a different level? Is it testing at the appropriate level (API vs. UI)?
Code Example — PR Review Checklist in Practice
// PR: "Add checkout flow E2E tests"// REVIEWER WOULD FLAG THESE ISSUES:// ❌ Issue 1: Non-descriptive test nametest('test checkout', async ({ page }) => { /* ... */ });
// Feedback: "Rename to describe the specific scenario being tested"// ✅ Suggested fix:test('guest user can complete checkout with credit card', async ({ page }) => { /* ... */ });
// ❌ Issue 2: Hard-coded waitawait page.waitForTimeout(2000);
// Feedback: "Replace with condition-based wait. What are we waiting for?"// ✅ Suggested fix:awaitexpect(page.getByText('Payment processed')).toBeVisible();
// ❌ Issue 3: Fragile selectorawait page.locator('#root > div > main > form > div:nth-child(3) > input').fill('...');
// Feedback: "Use semantic selector. What does this input represent to the user?"// ✅ Suggested fix:await page.getByLabel('Card number').fill('...');
// ❌ Issue 4: Test depends on external statetest('verify order appears in admin', async ({ page }) => {
await page.goto('/admin/orders');
awaitexpect(page.getByText('ORD-12345')).toBeVisible();
// Feedback: "This test assumes order ORD-12345 exists. Create your own order."
});
// ✅ Suggested fix:test('new order appears in admin panel', async ({ page, request }) => {
const order = awaitcreateOrderViaAPI(request);
await page.goto('/admin/orders');
awaitexpect(page.getByText(order.id)).toBeVisible();
});
// ❌ Issue 5: Multiple concerns in one testtest('checkout flow', async ({ page }) => {
// 50+ lines testing: add to cart, address form, payment, confirmation, email// Feedback: "This test does too much. Split into focused scenarios."
});
PR Review Checklist
## Automation PR Review Checklist### Test Design- [ ] Test names clearly describe the scenario
- [ ] Each test verifies ONE behavior
- [ ] Tests are independent (no order dependency)
- [ ] Test creates its own data (no shared fixtures mutation)
- [ ] Assertions validate user-visible outcomes
### Stability- [ ] No hard waits (waitForTimeout, Thread.sleep)
- [ ] Uses auto-waiting assertions (expect with retry)
- [ ] Selectors are resilient (role/label/testid, not CSS classes)
- [ ] Handles async operations explicitly
- [ ] No assumptions about element order
### Architecture- [ ] New page interactions added to page objects (not inline)
- [ ] Reuses existing fixtures and helpers
- [ ] No duplication of existing test coverage
- [ ] Appropriate test level (API vs UI)
- [ ] Follows project naming conventions
### CI Readiness- [ ] Passes with `--workers=4` (parallel safe)
- [ ] No hardcoded URLs or credentials
- [ ] Cleanup happens (fixtures with teardown)
- [ ] Reasonable timeout expectations for CI
Automated Checks for Test PRs
# .github/workflows/test-pr-quality.ymlname:TestPRQualityon:pull_request:paths:-'tests/**'-'src/pages/**'-'src/fixtures/**'jobs:quality-checks:runs-on:ubuntu-lateststeps:-uses:actions/checkout@v4-name:Checkforhardwaitsrun:|
if grep -r "waitForTimeout\|Thread.sleep\|setTimeout" tests/; then
echo "::warning::Found hard waits in tests. Consider condition-based waits."
fi
-name:Checkfor.onlyrun:|
if grep -r "\.only\b" tests/; then
echo "::error::Found .only in tests. Remove before merging."
exit 1
fi
-name:CheckforhardcodedURLsrun:|
if grep -rP "https?://(?!localhost)" tests/ --include="*.ts"; then
echo "::error::Found hardcoded URLs. Use baseURL from config."
exit 1
fi
-name:Verifyparallelexecutionrun:npxplaywrighttest--workers=4--repeat-each=2
Common Mistakes to Avoid
Approving without running — Always pull and run new tests locally
Only reviewing happy path — Check error handling and edge cases
Ignoring test data cleanup — Leaked data causes future flakiness
Not checking CI compatibility — Tests pass locally but fail in CI
Accepting duplicate coverage — More tests ≠ better if they test the same thing
Follow-up Questions
How do you handle disagreements about test design in reviews?
What's your threshold for requesting changes vs. suggesting improvements?
How do you review tests for code you don't know well?
How do you enforce review standards across a growing team?
Q24How do you handle a test that exposes a product bug?#
Objective
Assess the candidate's process for triaging, communicating, and managing test failures that represent genuine product defects.
Interview Answer
When a test fails and investigation reveals a product bug (not a test issue), my process has five steps:
1. Verify it's a real bug — Run the test repeatedly, check different environments, reproduce manually. Confirm the behavior violates requirements, not just test assumptions.
2. Isolate and document — Create the simplest reproduction case. Capture evidence: trace files, screenshots, steps to reproduce, expected vs. actual behavior.
3. File and communicate — Create a defect ticket with severity, impact, and reproduction steps. Notify the team immediately for critical/blocker issues (Slack, stand-up).
4. Decide test disposition — Three options:
Keep test, add known-failure annotation — Test documents the bug and will pass when fixed.
Skip with link to ticket — If failure blocks pipeline, skip temporarily with ticket reference.
Adjust assertion — If behavior is acceptable (not a bug, just different from old spec).
5. Track resolution — Follow up on the bug fix. When the fix ships, re-enable the test and verify it passes. The test now serves as regression protection.
Code Example — Playwright TypeScript
// Option A: Mark as known failure with annotationtest('discount applies to bulk orders @bug:JIRA-4521', async ({ page }) => {
test.info().annotations.push({
type: 'bug',
description: 'JIRA-4521: Discount not applied for quantities > 100',
});
// Test documents the expected behaviorawait page.goto('/cart');
await page.getByLabel('Quantity').fill('150');
await page.getByRole('button', { name: 'Update' }).click();
// This will fail until JIRA-4521 is fixedawaitexpect(page.getByTestId('discount-line')).toBeVisible();
});
// Option B: Skip with reference (if blocking CI)
test.skip('discount applies to bulk orders', async ({ page }) => {
// SKIPPED: Product bug JIRA-4521 — discount calculation fails for qty > 100// Re-enable when fix is deployed. PR: https://github.com/org/repo/pull/789
});
// Option C: Fixme annotation (test runs, failure expected)test('bulk discount calculation', async ({ page }) => {
test.fixme(true, 'Bug JIRA-4521: Fails for qty > 100. Fix expected Sprint 14.');
});
// Option D: Conditional skip based on environmenttest('feature X works correctly', async ({ page }) => {
test.skip(
process.env.ENV === 'staging',
'Bug JIRA-4521: Only affects staging due to config difference'
);
// ... test code
});
// Regression test after bug is fixedtest('regression: discount applies to bulk orders (JIRA-4521)', async ({ page }) => {
// This test was originally written to expose JIRA-4521// Now serves as permanent regression protectionawait page.goto('/cart');
await page.getByLabel('Quantity').fill('150');
await page.getByRole('button', { name: 'Update' }).click();
awaitexpect(page.getByTestId('discount-line')).toBeVisible();
awaitexpect(page.getByTestId('discount-amount')).toContainText('15%');
});
Test Failed
│
▼
Is it a test issue? (selector changed, timing, data)
│
YES ──→ Fix the test
│
NO (product behavior is wrong)
│
▼
Is it blocking CI pipeline?
│
YES ──→ Skip test with ticket reference
│ Notify team immediately
NO
│
▼
Is it a critical user flow?
│
YES ──→ File as P1/Critical
│ Consider hotfix
NO
│
▼
File as P2/P3
Annotate test with @bug:TICKET-ID
Keep test running (failure documented)
Common Mistakes to Avoid
Fixing the test to pass — Hiding a bug by adjusting assertions
Silently deleting failing tests — Loses coverage and hides issues
Not communicating urgency — Critical bugs need immediate attention, not just a ticket
No evidence in bug report — Developer can't reproduce without steps/traces
Forgetting to re-enable skipped tests — Create a recurring check for skipped tests
Follow-up Questions
How do you prevent accumulation of skipped tests?
How do you decide between skip and known-failure annotations?
Who decides the priority of a bug found by automation?
How do you track the age of unresolved test-found bugs?
Q25How do you migrate a Selenium suite to Playwright?#
Objective
Evaluate the candidate's practical experience and strategic approach to framework migration without losing coverage or team velocity.
Interview Answer
Migration from Selenium to Playwright is a high-value investment — Playwright offers faster execution, built-in auto-waiting, better debugging (traces), and native TypeScript support. But migration must be incremental, not a big-bang rewrite.
My migration strategy has four phases:
Phase 1: Parallel setup (1-2 weeks) — Set up Playwright alongside Selenium. Both run in CI. New tests are written in Playwright immediately. Existing tests continue running in Selenium.
Phase 2: Pattern establishment (2-4 weeks) — Migrate 5-10 representative tests covering different patterns (forms, tables, navigation, auth). Establish page object conventions, fixture patterns, and CI integration. This becomes the template.
Phase 3: Incremental migration (ongoing) — Migrate tests module-by-module. Prioritize: most-flaky Selenium tests first (biggest stability gain), then critical paths, then remaining tests. Each migrated module removes corresponding Selenium tests.
Phase 4: Decommission (final) — Once Selenium test count reaches zero, remove Selenium infrastructure, dependencies, and CI jobs.
Key rules: Never rewrite and migrate simultaneously. Port tests 1:1 first, then improve. Track migration progress with a burndown chart.
Week 1-2: [████░░░░░░░░░░░░░░░░░░░░] Setup Playwright, first 5 tests
Week 3-4: [████████░░░░░░░░░░░░░░░░] Patterns established, 15 tests migrated
Week 5-8: [████████████████░░░░░░░░] Critical paths migrated (60%)
Week 9-12: [████████████████████████] Complete, Selenium removed
Key Metrics During Migration:
- No coverage gaps (both suites run until handoff)
- New tests ONLY in Playwright from Day 1
- Flaky Selenium tests migrated first (biggest win)
- Team trained in parallel (pair programming on migrations)
Common Mistakes to Avoid
Big-bang rewrite — Attempting to migrate everything at once introduces risk
Translating anti-patterns — Don't port Thread.sleep or CSS selectors; improve during migration
Losing coverage during transition — Both suites must run until module is fully migrated
Not training the team — Developers need Playwright knowledge before they contribute
Keeping Selenium "just in case" — Set a decommission date and stick to it
Follow-up Questions
How do you handle Selenium custom utilities that have no Playwright equivalent?
How do you decide migration order for test modules?
How do you maintain team velocity during migration?
What's the minimum viable Playwright setup to start migration?
Architecture matters more than tools — A well-designed framework with clear layers (test, interaction, infrastructure) survives tool changes and team growth.
Stability comes from design, not retries — Proper selectors, condition-based waits, test isolation, and controlled data eliminate flakiness at the source.
CI integration is the delivery mechanism — Tests that don't run automatically on every change provide minimal value. Design for fast feedback in tiers.
Measure what matters — ROI isn't test count. It's confidence to ship, bugs prevented, and time returned to the team.
Migration is a journey — Moving between frameworks requires incremental execution, parallel running, and team enablement.
Competency Matrix
Level
Automation Skill
Junior
Can write and run individual tests
Mid
Designs page objects, manages test data, integrates with CI