70Interview Q&A Mega-Bank
What this is
200+ extra interview questions organised by topic. Cram sheet to skim the day before. All answers concise — full context lives in the relevant module.
Playwright Fundamentals
Difference between page.locator and page.$?
locator: re-queried description, never stale, auto-retries.
page.$: one-time ElementHandle, can go stale. Modern code uses locator everywhere.Can a single test have multiple browser contexts?
Yes.
const ctx2 = await browser.newContext(). Useful for testing two users (seller + buyer) in the same test.What does waitFor with state=detached do?
Waits for the element to leave the DOM. Useful for "spinner disappears" or "modal closes".
How do you handle file download to memory (no disk)?
const stream = await download.createReadStream(). Read chunks; useful for validating CSV contents without writing to disk.What does page.exposeFunction do?
Registers a Node-side function callable from the page's JS. Used for postMessage capture or letting page code call test helpers.
How to set a cookie before navigation?
await context.addCookies([{ name, value, url }]). Set before goto.How to inject script into every new page?
await context.addInitScript(() => { window.X = ... }). Runs on every new page before any other script.Difference between page.fill and page.type?
fill clears + sets in one op (instant). type/pressSequentially types char-by-char with delay (fires per-key events).
How to disable JavaScript on a page?
newContext({ javaScriptEnabled: false }). Useful for SSR / no-JS rendering tests.What's page.waitForLoadState('networkidle') for?
Waits until no network activity for 500ms. Useful for SPAs but flaky on apps with long-polls. Prefer specific assertions.
Locators & Selectors
How to target the "Save" button only inside a specific section?
page.getByRole('region', { name: 'Profile' }).getByRole('button', { name: 'Save' }). Chain locators.Locator chain vs CSS descendant selector?
Chain re-queries each segment independently, more refactor-resilient. CSS is one query, faster but more brittle to mid-page changes.
Why is getByText('Submit') a bad locator for a button?
It matches any element with that text — could be a div, span, or hidden text. Prefer getByRole('button', { name: 'Submit' }) which restricts to interactive buttons.
How to handle dynamic IDs?
Don't use them. Use role+name. Failing that, use data-testid (stable contract with devs).
What's a "false-positive locator"?
A locator that matches the wrong element silently — e.g. CSS class that's reused elsewhere. Strict mode prevents this by failing when multiple match.
Fixtures & Parallelism
Can fixtures depend on each other?
Yes — list as parameter:
apiUser: async ({ apiClient }, use) => { ... }. Playwright resolves topologically.Worker fixture scope = ?
Created once per worker (process), shared across all tests in that worker. Good for expensive setup like DB pool, auth token.
How to skip a test on a specific browser?
test.skip(browserName === 'firefox', 'reason') at top of test.fullyParallel: true vs serial mode — when each?
fullyParallel for independent tests (most). serial when tests share state intentionally (multi-step flow); accept that one failure fails the rest.
Can two projects share a fixture?
Yes — fixtures defined in shared module imported by both. Override per project via
test.use({ ... }).Network & Mocking
Difference between route.fulfill and route.continue?
fulfill: respond with fake data (no real request). continue: let the real request proceed (optionally modified). Use fulfill for full mock, continue for inject-then-pass.
How to mock only the third call to an endpoint?
Counter in the handler:
let n=0; await page.route(url, r => ++n === 3 ? r.fulfill(...) : r.continue()).Can you mock different responses for different test cases?
Yes — set the route inside each test with its specific response.
How to simulate offline?
await context.setOffline(true). Or per-route route.abort('failed').What happens to in-flight requests when you call route after the navigation started?
Route handlers only apply to requests initiated after handler registration. Always register handlers before triggering the navigation.
CI / Flakiness
Test fails 1/20 runs — what?
It's flaky. Quarantine, repro with --repeat-each=20 locally, fix root cause (usually missing await, race, or extracted-value assertion). Lift quarantine when --repeat-each=100 green on CI.
How to capture trace only on failure?
trace: 'retain-on-failure' or 'on-first-retry'. The latter is cheaper — trace only when first attempt failed.Why does my test fail with "Element is hidden"?
Element exists but has display:none, visibility:hidden, opacity:0, or zero size. Wait for visibility before interaction; auto-wait does this for action methods.
How to inspect why a locator timed out?
Trace viewer shows DOM at failure step. The "Locator" tab indicates what matched (or didn't) and why. Better than reading the error text alone.
Should --workers=1 fix the flake?
It eliminates parallel-test data collisions. If flake disappears at --workers=1, you have a data isolation bug. Fix data sharing, not workers count.
API Testing
How to test pagination?
Call with page=1, assert N items. Follow next link/cursor. Assert page=last has <= N items. Test empty page, out-of-range page.
How to test rate limiting?
Fire requests in tight loop. Assert 429 after N. Inspect Retry-After header. Reset state between tests to avoid bleed.
How to handle async API (job creation)?
POST returns 202 + job id. Poll GET /jobs/{id} with
expect.poll until status = 'done' or timeout.API returns 200 with errors in body — bug?
Depends. GraphQL — by design. REST — usually a bug; should be 4xx. Assert both status AND body shape to catch this.
How to test webhook receiver?
Either spin up a test webhook server (Express) and configure your app to point at it; or use a tool like webhook.site. Verify your handler processed the payload correctly via DB / next API call.
Database Testing
How to assert a record exists in Postgres from Playwright test?
Inject a
db fixture with pg pool. Query in test, assert row count. Cleanup in teardown.How to test soft-delete?
Delete via UI/API; query DB ensuring row exists with
deleted_at set. Distinct from hard delete.How to handle test data accumulation?
Per-test cleanup in fixture teardown. Nightly job deletes everything tagged created_by='qa-suite' older than 7 days.
Transaction rollback for test isolation — pros/cons?
Pro: instant cleanup, no leftovers. Con: doesn't work if test code commits its own TX or uses multiple connections. Works best for single-connection unit tests.
JS / TS
What's the output: [1,2,3].map(parseInt)?
[1, NaN, NaN]. parseInt takes (string, radix); map passes (value, index). So parseInt('1',0)=1, parseInt('2',1)=NaN, parseInt('3',2)=NaN.
Why does a == b return true for null == undefined?
Special spec rule. Use === to avoid surprises.
What is hoisting?
var declarations + function decls lifted to top of scope. let/const lifted too but in TDZ — accessing before declaration throws.
Why arr.forEach(async fn) doesn't await?
forEach doesn't accept callback's return value. Use
for...of with await for sequential, or Promise.all(arr.map(fn)) for parallel.What's the difference between new Set() and an object?
Set holds any value (including objects), preserves insertion order, fast .has() and .size. Object uses string keys, no built-in size, prototype pollution risk.
Why is {} === {} false?
Reference comparison. Two distinct objects. To compare values, use deepEqual or JSON stringify (for serializable data).
What's a closure leak?
Closure holds reference to large outer-scope object. As long as closure lives (event listener, timer), GC can't reclaim. Remove listener / clear timer on cleanup.
What's TS never for?
Type that has no values. Returned by functions that always throw or infinite-loop. Used in exhaustive switch checks.
Conditional types — give a real use case?
Extracting Promise inner type:
Awaited<Promise<T>>. Or function return type: ReturnType<typeof fn>. Both use conditional + infer internally.What's as const?
Narrows inferred type to literal values.
const cfg = { mode: 'dark' } as const → mode type is 'dark', not string.DSA
Binary search on a rotated sorted array?
Compare mid to lo to detect which half is sorted; check if target is in that half; binary-search there. O(log n).
Why is a hashmap O(1) on average?
Good hash distributes keys uniformly across buckets. Each bucket holds ~O(1) entries on average. Resize doubles capacity at load factor 0.75, keeping amortised O(1) insert.
How to find duplicate in O(n) time + O(1) space?
Floyd's cycle detection on value-as-pointer interpretation (when values in 1..n range). Or in-place sign marker (negate value at index abs(x)-1; collision → duplicate).
BFS or DFS for tree level order?
BFS — queue per level naturally gives level order. DFS can do it with depth tracking but BFS is cleaner.
How to detect cycle in undirected graph?
Union-Find: for each edge, if endpoints already in same set → cycle. Or DFS tracking parent: a visited non-parent neighbour → cycle.
Why is heapsort O(n log n) but slower than quicksort in practice?
Cache-unfriendly. Heap operations jump around the array; quicksort scans linearly. Same complexity, worse constant.
Sliding window vs two pointer — same?
Sliding window IS a two-pointer pattern where both move forward, expanding/shrinking to satisfy a constraint. Two-pointer also covers opposite-end traversal (palindrome, sorted pair).
0/1 knapsack vs unbounded — loop direction?
0/1: weights inner loop DESCENDING (prevents re-use of item). Unbounded: ASCENDING (enables re-use). Subtle but critical.
How does Dijkstra's heap implementation save time?
Without heap: O(V²) to find min unprocessed each step. With heap: O((V+E) log V) — extract min is O(log V), relax is O(log V) per edge.
What's the longest substring without repeats algorithm?
Sliding window + hashmap of last-seen index. Expand right; if char in current window, jump left past it. Update best. O(n).
System Design
What's a noisy neighbour problem?
One tenant on shared infra hogs resources, degrading others. Mitigate: quotas, isolation (separate clusters / dedicated nodes), throttling.
Why use a queue between web and worker?
Decouple producer rate from consumer rate. Smooth bursts. Survive consumer downtime (queue holds work). Retry semantics.
How does CDN cache invalidation work?
Purge by URL or tag via API. Or versioned URLs (filename with hash) → no invalidation needed. Or short TTLs and accept eventual freshness.
What's a hot partition?
One Kafka partition (or DB shard) getting most traffic. Fix: better partition key (hash on user, not on date); sub-key for super-hot users.
Why is consistent hashing better than mod?
mod(N) moves ~all keys when N changes. Consistent hashing moves ~1/N. Critical for cache fleets that auto-scale.
What's a write-ahead log?
Append-only log of changes; durable on disk before applying to data file. Crash recovery replays from WAL. Used by Postgres, MySQL InnoDB, RocksDB, Kafka.
Why is exactly-once delivery hard?
Network can drop ack between consumer and broker. Without dedup, redelivery → duplicate processing. True exactly-once requires transactional producer + idempotent consumer or distributed TX.
What does it mean to "shed load"?
Refuse some requests (429 / 503) when overloaded so the system stays partially up. Better than full collapse. Combine with priority routing (prioritise critical users).
How does service discovery work?
Service registers itself with a registry (Consul, Eureka, k8s service). Clients query registry to find healthy instances. DNS-based or sidecar-proxied (Envoy).
What's a leader's split-brain problem?
Network partition makes two nodes think they're the leader. Both accept writes → divergence. Quorum-based consensus (Raft) prevents this — only majority side can commit.
Behavioral
"Tell me about a time you missed a deadline" — structure?
Own it. Situation + cause. What you did to recover (re-scope, alert stakeholders early, pull in help). Result + what you'd do differently. No blame on others.
"Tell me about a disagreement"
Specific disagreement (technical, not personal). What you proposed + why. How you listened to the other view. How you reached resolution (data, prototype, escalation as last resort). Outcome.
"Why this company?"
Researched. Specific (product, engineering blog, public talk). Connect to your goals. Avoid generic "great culture".
"Why are you leaving?"
Forward-looking. What you want NEXT, not what's wrong now. "I want to own end-to-end test infra" beats "my manager is bad".
"What's your weakness?"
Real weakness + concrete steps you're taking. Avoid faux-weaknesses ("I work too hard"). Show self-awareness.
"Walk me through your proudest project"
STAR with numbers. Tech detail enough to show depth. End with what you learned + scaled to others.
Career & Levels
SDE-1 → SDE-2 promotion criteria?
Consistently owns features end-to-end (not just tasks). Designs components. Reviews code substantively. Mentors juniors informally. Reliably ships without close supervision.
What separates senior from staff engineer?
Scope. Senior owns one system; staff influences many. Senior solves hard problems; staff defines which problems to solve. Senior writes code; staff writes docs that change how others write code.
How to grow from SDET to staff SDET?
Move from "write tests" to "design test platform". Lead initiatives across teams. Mentor other SDETs. Publish internal best practices. Influence dev culture (TDD, contract testing). Quantify business impact in promo doc.
Should an SDET learn dev skills?
Yes. The best SDETs read product code fluently, propose fixes, and contribute to dev tooling. Don't have to be a great app developer, but "I can't read the code" caps your impact at junior.
How to negotiate offer?
Wait for first offer; don't reveal expectations early. Get competing offers if possible. Total comp matters (base + equity + bonus + perks). Decline politely if low; counter with concrete number. Use levels.fyi for market data.
Real-world SDET scenarios
Test environment is down all morning — what?
Communicate to PM + team early. Switch to whatever can proceed (unit tests, manual exploratory on prod-like local). Don't claim productive work that isn't happening. Help diagnose if possible.
Dev says "this test is wrong, my code is fine"
Pull the trace. Read together. If test is wrong: thank them, fix it. If code is wrong: show the evidence calmly. Avoid framing as a contest.
PM wants you to skip tests to ship faster
Quantify risk: "skipping these means we likely miss X class of bug; last time that cost us Y". Offer alternatives (smaller smoke set, post-deploy monitoring). Document the decision so accountability is clear.
Found a critical bug 1 hour before release
Triage severity vs impact with PM + eng lead. Options: hotfix + delay, ship behind flag (off), accept + monitor. Decision is shared, not yours alone.
Test infra costs ballooned 3× in a quarter
Audit: per-PR vs per-merge runs, parallel-worker sizing, test selection effectiveness, cloud farm minutes. Often 80% comes from 20% of tests/PRs. Optimise top offenders; gate non-essential tests behind labels.
New senior joins and rewrites your framework
Listen to the why. If technically sound — embrace, learn. If not — push back with data (test stability metrics before/after). If they're more senior + you've lost, support the migration or look elsewhere.
Tools quick-fire
Which tool: testing a Stripe checkout flow?
Playwright for UI + API setup; mock Stripe for negative paths; real Stripe test mode for happy path; idempotency-key test; DB assertion for order persistence.
Which tool: load-testing a REST API?
k6 for modern code-first; JMeter if you have legacy plans / non-tech testers. Gatling for highest throughput-per-host.
Which tool: testing GraphQL subscription?
graphql-ws client for the WS connection; Playwright drives a mutation that triggers the subscription; assert received payload.
Which tool: visual regression on a design system?
Playwright toHaveScreenshot or Percy / Chromatic for component-by-component snapshots. Run via Storybook stories.
Which tool: smoke-monitor prod for 99.9% uptime?
Synthetic monitoring (Datadog Synthetics, Checkly, or self-hosted Playwright on cron). Critical user journey every 5 min; page on-call on 2 consecutive failures.
Misc cheat-sheet questions
What's a "stale element" error in Selenium and how does Playwright avoid it?
Selenium WebElement is a handle to a found node; DOM re-render invalidates. Playwright Locator is a re-queried description; never stale.
How does Playwright auto-wait actually wait?
Actionability loop polling ~50ms: attached, visible, stable, enabled, receives events. Each check re-queries the DOM. Action timeout default 30s.
Why is BrowserContext faster than Browser per test?
Browser launch = OS process start (~1s). Context = memory allocation inside running browser (~10-50ms). 100× faster for test isolation.
Cookies vs localStorage vs sessionStorage?
Cookies: sent with every request, server-readable, httpOnly possible. localStorage: client-only, persists. sessionStorage: client-only, cleared on tab close. Auth tokens → httpOnly cookie. UI prefs → localStorage.
HTTP/2 server push — still used?
Mostly removed (Chrome dropped it 2022). 103 Early Hints + preload are the modern replacement.
What's a quine?
Program that outputs its own source code. Fun puzzle; not interview-relevant.
What's the Y combinator?
Higher-order function enabling recursion in lambda calculus without naming the function. Theoretical interest; not practical.
One thing every SDET should set up on day 1?
Reliable local dev: clone repo, npm i, run tests once. If the basic dev loop is broken, fix that before writing new tests.
Bonus — the questions that catch people out
"What's a flaky test you couldn't fix?"
Be honest. Specific test. What you tried. Why root cause was elusive (third-party API, race in the app). What workaround you used. Don't pretend you've never been beaten by a flake.
"Show me your worst test"
Open your real repo (or paste a known weak one). Walk through what's wrong + what you'd improve. Self-aware critique is gold; pretending it's all perfect is a red flag.
"Why should we hire you specifically?"
Concrete past impact + specific match to this role. Avoid "I'm passionate about quality" — everyone says that. "I led the migration that cut your competitor's CI time from 40 to 7 minutes" — different signal.
"Tell me something you wish you'd learned earlier"
Specific lesson. Concrete cost of not knowing. How you learned it. What you do differently now. Shows reflection + growth mindset.
"What would you do in your first 30/60/90 days here?"
30: shadow team, learn codebase, run all tests, document one gap. 60: ship a small improvement (faster CI, fixed flake), get to know each dev pair. 90: lead one initiative (e.g. introduce contract testing pilot). Numbers + tangible deliverables.