Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 35 ยท Practice and Review

Interview Questions

Prepare for browser-testing interviews with 36 questions and short answers on concepts, waiting, selectors, network, CI, and Cypress versus Playwright.

Interviewers for test-automation and front-end roles rarely ask for syntax from memory. They want to know whether you understand why browser tests behave the way they do: why they flake, why waiting works the way it does, how you choose a selector, and when you would not write an end-to-end test at all. This lesson collects 36 questions with short answers. Say the answers aloud in your own words; reciting them never works as well as understanding them.

The answers describe the current behavior of Cypress and Playwright as we know it. Defaults and features change between versions, so when you give a number (a timeout, for example), say "by default" and mention that it is configurable. Cypress and Playwright cannot run on this site, so the code in the answers is read-only. Two runnable stand-ins near the end let you check two of the ideas with real arithmetic and a real queue.

Concepts

1. What is an end-to-end test, and how is it different from a unit test? An end-to-end (e2e) test drives the application the way a user does, through a real browser, the real front end and usually a real or stubbed back end. A unit test checks one function or component in isolation. E2e tests give high confidence about whole journeys, but they are slower and more fragile, so you write few of them. See What End-to-End Testing Is.

2. What is the test pyramid? A guideline: many fast unit tests at the bottom, fewer integration tests in the middle, and a small number of e2e tests on top. The shape reflects cost versus confidence. A "pyramid" with a heavy top (hundreds of browser tests) is slow, flaky and expensive. See Testing Strategy and the Test Pyramid.

3. What should you test end to end, and what should you not? Test critical user journeys: sign-up, login, search, checkout. Do not test every validation rule, every calculation or every error code through the browser; do those at a lower layer. Also avoid testing third-party sites you do not control.

4. How do Cypress and Playwright differ architecturally? Cypress runs its test code inside the browser, in the same run loop as your application, with a Node process in the background for tasks and plugins. Playwright runs tests in a separate Node (or Python, Java, .NET) process and drives browsers over a protocol. The in-browser design gives Cypress its live-reload runner and easy access to the app; the out-of-process design gives Playwright multiple tabs, multiple browser contexts and several languages. See Cypress vs Playwright.

flowchart LR
  subgraph CY["Cypress"]
    direction TB
    CB["Browser<br/>app and test code together"]
    CN["Node process<br/>plugins, tasks"]
    CB <--> CN
  end
  subgraph PW["Playwright"]
    direction TB
    PT["Test runner process"]
    PB["Browser<br/>driven over a protocol"]
    PT <--> PB
  end

Where the test code lives: inside the browser for Cypress, outside it for Playwright.

5. Which browsers and languages does each support? Playwright drives Chromium, Firefox and WebKit, and offers JavaScript/TypeScript, Python, Java and .NET. Cypress targets Chrome-family browsers, Edge, Firefox and Electron, with WebKit support still experimental, and tests are written in JavaScript or TypeScript. Check the current docs before you commit to a claim; support evolves.

6. When would you choose Cypress, and when Playwright? Cypress shines for front-end teams who want an interactive runner and fast feedback while building. Playwright shines when you need multiple tabs or users in one test, cross-browser coverage including WebKit, non-JavaScript languages, or built-in parallelism and tracing. Either is a sound choice; consistency within a team matters more than the label.

7. What does "test isolation" mean? Each test starts from a known, clean state and does not rely on another test having run first. Cypress clears cookies, local storage and session storage between tests by default. Playwright creates a fresh browser context per test. Isolation lets tests run in any order and in parallel.

Waiting and flakiness

8. What is a flaky test? A test that sometimes passes and sometimes fails on the same code. Typical causes are timing (acting before the page is ready), shared data, animations, network variance, and dependence on test order or on the current date.

9. How does Playwright wait automatically? Before an action such as click, Playwright runs actionability checks: the element must be attached, visible, stable (not animating), enabled, and able to receive events at the click point. It retries until they pass or the timeout expires. See Auto-Waiting in Playwright.

10. What are web-first assertions? Assertions such as await expect(locator).toHaveText('Done') retry until the condition is true or the timeout is reached (five seconds by default for expect). They replace "read a value, then compare it", which only checks a single moment.

11. How does Cypress retry? Cypress retries queries (cy.get, .find, .contains) together with the assertions that follow them (.should). It does not retry actions such as .click. The default command timeout is four seconds. See Assertions That Retry.

12. Why is cy.wait(2000) or page.waitForTimeout(2000) a code smell? It guesses a duration: too short on slow CI, wasteful on a fast machine. Wait for a condition instead: an assertion, a route alias, a response, or a URL change.

13. How do you wait for a network call to finish? In Cypress, alias the intercept and cy.wait('@alias'). In Playwright, start page.waitForResponse(...) before the action that triggers the request, or wait for the visible result with an assertion.

JavaScript
// Cypress (read-only)
cy.intercept('POST', '/api/orders').as('createOrder')
cy.contains('button', 'Place order').click()
cy.wait('@createOrder').its('response.statusCode').should('eq', 201)
TypeScript
// Playwright (read-only)
const responsePromise = page.waitForResponse('**/api/orders');
await page.getByRole('button', { name: 'Place order' }).click();
const response = await responsePromise;
expect(response.status()).toBe(201);

14. Why does the Playwright example create the promise before the click? If you start listening after the click, a fast response may already be gone. Create the promise first, trigger the action, then await the promise.

15. Should you use test retries? Retries are a safety net, not a cure. They keep a pipeline green while you investigate, and Playwright marks a test that passed on retry as "flaky" so it stays visible. Track flaky tests and fix them; a suite that depends on retries hides real problems. See Finding and Fixing Flaky Tests.

16. How do you find the cause of a test that only fails in CI? Collect evidence: the trace or video and screenshot from the failed run, the browser console and network log, and the exact versions. Then compare the environment: CPU speed (slower CI exposes timing bugs), viewport, time zone, locale, and data. Reproduce locally with the same container image and with CPU throttling or repeated runs.

Selectors and structure

17. How do you choose a selector? In order of preference: by role and accessible name (what a user perceives), by label or visible text, by a dedicated test id (data-testid, data-cy), and only last by CSS structure. Avoid generated class names, positions (:nth-child(3)) and long XPath. See Writing Selectors That Do Not Break.

18. Why is a role-based locator good? It matches what assistive technology exposes, so it works like a user does and also verifies accessibility basics: a clickable div without a role would not be found. It also survives class and layout refactors.

19. What is strictness in Playwright? A locator that matches more than one element throws when you perform an action on it, instead of silently picking one. Narrow it by scoping, filter, or an explicit first()/nth() when you really mean it. See Locators in Playwright.

20. What does within do in Cypress? .within(() => { ... }) scopes every cy.get and cy.contains inside the callback to the selected element, which is the standard way to work inside one table row or one card. See Selecting Elements in Cypress.

21. What is the page object pattern, and what are its risks? A class or module per page or component that owns selectors and exposes user-intent methods. The benefit is one place to fix when markup changes. The risks are thin wrappers, hidden assertions and deep inheritance. Keep assertions in the test. See Page Objects and Better Test Structure.

22. What is a fixture in each tool? In Cypress, a fixture is usually a static data file (cypress/fixtures/users.json) loaded with cy.fixture or used in cy.intercept. In Playwright, a fixture is a unit of setup and teardown provided to tests through test.extend. The same word means two things, so clarify which one you mean. See Hooks, Fixtures and Custom Commands.

Network and data

23. How do you mock a network response? Cypress: cy.intercept('GET', '/api/items', { body: [...] }). Playwright: page.route('**/api/items', route => route.fulfill({ json: [...] })). Register it before the page makes the request. See Intercepting and Mocking Network Requests.

24. When should you stub the network, and when use the real back end? Stub to test states that are hard to produce (errors, empty lists, slow responses) and to make tests fast and deterministic. Keep some tests against the real back end (or a realistic test environment) so that the contract between front and back end is actually exercised.

25. How do you test an error state? Return an error from the stub (status: 500, route.abort(), or Cypress's forceNetworkError: true), then assert that the page shows an understandable message and offers recovery such as a Retry button.

26. How do you avoid logging in through the UI in every test? Log in once by API or through the form, then reuse the session: cy.session() in Cypress, storageState saved by a setup project in Playwright. Keep one test that exercises the login form itself. See Test Data and Logging In Fast.

27. How do you manage test data? Create it through API calls or a test-only endpoint, make it unique per test (for example, unique emails), and delete it in teardown. Never share mutable data between tests, and never run destructive tests against production.

28. Can you test an API with these tools? Yes: cy.request and Playwright's request fixture send HTTP calls with no browser page. They are useful for setup, teardown and direct API checks. See Testing APIs Directly.

Tool-specific behavior

29. Why can't you assign cy.get() to a variable and use it later? Cypress commands are enqueued, not executed immediately, and they yield results to the next command. A variable holds a chain object rather than the element or text. Use .then(), aliases (.as()), or cy.wrap. See How Cypress Commands Really Work.

30. Can you use async/await in Cypress tests? Not in the usual way. Cypress commands are not promises, and await cy.get() does not do what you expect. You can use async code inside .then() callbacks or tasks. Playwright tests, in contrast, are ordinary async functions and await every action.

31. How do the tools handle multiple tabs and windows? Playwright can control several pages and browser contexts in one test, so a popup is a new Page object. Cypress works in a single tab; tests typically stub window.open or check a link's href instead. For different origins, Cypress offers cy.origin(). See Iframes, New Tabs and Dialogs.

32. How do you work with iframes? Playwright has page.frameLocator('iframe[title="Payment"]'), which returns a locator scope you can chain from. Cypress has no built-in iframe command, so teams use a small custom command or a plugin that gets the frame's body and wraps it.

33. What is a trace in Playwright? A recorded timeline of a test: each action, DOM snapshots before and after, network requests, console messages and screenshots, viewable with npx playwright show-trace. Teams typically record traces on first retry so that failed CI runs can be replayed. See Traces, Videos and Reports.

CI and scale

34. How do you run these tests in CI? Install dependencies, install the browsers (for Playwright, npx playwright install --with-deps), start or point to the app, run headless, and upload artifacts (reports, traces, videos, screenshots) when a run fails. Many teams use the official Docker images for matching environments. See Running Tests in CI.

35. How do you make a large suite faster? Run in parallel (Playwright workers and fullyParallel, --shard=1/4 across machines; Cypress parallelization is organized through Cypress Cloud), seed data by API instead of the UI, reuse login sessions, stub slow third-party calls, and delete tests that duplicate lower-level coverage. See Parallel Runs, Sharding and Speed.

36. How do you decide whether a test failure is a product bug or a test bug? Read the error and the evidence. A selector that no longer matches after a redesign is a test bug. An assertion that fails with the correct selector, on every run, usually exposes a product bug. A failure that appears in some runs only is a flake; investigate timing and shared state before blaming either.

Try two of the ideas

Question 29 says commands are enqueued. The stand-in below shows the effect: the "test" body finishes running before any command executes, which is why console.log calls inside a Cypress test body appear before the commands' effects.

JS Why queued commands run later

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Question 15 says retries are a safety net. The stand-in below does the arithmetic that interviewers like to hear: a small per-test flake rate becomes a large suite-level failure rate, and retries shrink it dramatically, but they do not fix the cause.

JS What a small flake rate does to a suite

Press Run (or Ctrl + Enter) to see the console output here.

No output.

For a 2 percent flake rate and 100 tests, the whole suite goes green only about 13 percent of the time without retries. With two retries it is above 99 percent, which is why teams enable them, and why they must also track which tests needed a retry.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement about retrying is correct?

    Cypress retries cy.get-style queries together with their assertions. Actions are not retried, and test-level retries only hide flakiness.
  2. 2. How is Playwright's architecture different from Cypress's?

    That difference explains many others: multiple tabs and languages in Playwright, and the in-browser runner experience in Cypress.
  3. 3. Why create the waitForResponse promise before clicking?

    Starting the listener first guarantees you cannot miss the response.
  4. 4. A suite of 100 tests has a 2 percent flake rate per test. Roughly how often does it pass without retries?

    0.98 to the power of 100 is about 0.13. Small per-test flake rates add up across many tests.
  5. 5. Which locator is the best default for a button labelled Save?

    Role and accessible name match what users and assistive technology see, and they survive styling changes.

Summary

  • Be ready to explain why: architecture, retry-ability, isolation and the test pyramid explain most behavior.
  • Wait for conditions (assertions, responses, URLs), never for fixed durations.
  • Choose selectors by role, label, then test id; scope them; avoid brittle structure.
  • Stub the network for hard-to-reach states and keep some tests on the real back end.
  • Seed data and log in by API, keep tests isolated, and track flaky tests instead of hiding them.
  • Know the two tools' main differences, but argue for consistency and fit, not for a favorite.

Next: Cheat Sheet