Selenium Middle cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. What does
FluentWaitadd over a basicWebDriverWait?new FluentWait<>(driver) .withTimeout(Duration.ofSeconds(15)) .pollingEvery(Duration.ofMillis(300)) .ignoring(StaleElementReferenceException.class);Correct answer: Custom polling interval and exceptions to ignore while waiting
WebDriverWait is a FluentWait with defaults. Ignoring stale errors helps with re-rendering components.
2. How do you wait for a custom condition, e.g. a counter showing 5?
wait.until(d -> d.findElement(By.id("count")).getText().equals("5"));Correct answer: Pass a lambda that returns true or a non-null value when ready
until accepts any function of the driver. It repeats until the result is true or non-null, or the timeout fires.
3. Why can
@FindByfields withPageFactorycause stale element errors?Correct answer: The proxy may hold an element that was re-rendered after the first lookup
With caching (@CacheLookup) the element is reused even after the DOM changed. Many teams use By locators and find on each call instead.
4. What is a page component (or fragment) object?
Correct answer: An object for a reusable part, like a header or table, used by several pages
Components avoid copying the same header locators into every page object.
5. What does a fluent page object method return after navigation?
public DashboardPage loginAs(User u) { ...; return new DashboardPage(driver); }Correct answer: The page object of the page the user lands on
The test reads like a flow and the types show where navigation goes.
6. Where should the constructor of a page object check that it's on the right page?
Correct answer: It should wait for a key element so wrong navigation fails early
Failing at the right place gives clear errors instead of NoSuchElement three steps later.
7. What is the purpose of a driver factory?
Correct answer: Create configured drivers from settings like browser, headless or Grid URL
Tests ask for a driver and don't care how it's built; switching to Grid is a config change.
8. How do you run Selenium tests in parallel with TestNG?
Correct answer: Set
parallelandthread-countin testng.xml, one driver per threadparallel can be methods, classes or tests. Shared static drivers break parallel runs.
9. What are the main parts of Selenium Grid 4?
Correct answer: Router, distributor, session map, event bus and nodes
In standalone or hub-and-node mode they run together; in distributed mode each part scales separately.
10. Why are official Selenium Docker images popular for Grid?
Correct answer: They give ready browser nodes with matching drivers, easy to scale
docker-selenium images include Chrome, Firefox or Edge nodes and optional video recording.
11. What are capabilities in WebDriver?
Correct answer: Settings for the browser and session you want, like browserName
Browser options classes like ChromeOptions build capabilities. Vendor options go under prefixed keys.
12. What does WebDriver BiDi enable that classic WebDriver couldn't?
Correct answer: Browser events, like console logs and network requests, as they happen
Classic WebDriver is request-response. BiDi adds a two-way channel for events and network control.
13. How can a Selenium 4 test fail when the page logs a JavaScript error?
Correct answer: Listen to console events via BiDi and assert none occurred
JS errors often explain broken UI before any assertion runs.
14. How do you test a file download in Chrome with Selenium?
Correct answer: Set the download directory in Chrome prefs and wait for the file
Headless Chrome also needs downloads allowed. On Grid, Selenium 4 can fetch downloaded files from the node.
15. What does the page load strategy
eagerchange?Correct answer: get returns after DOMContentLoaded, not waiting for images
normal waits for the load event, none returns immediately. Explicit waits still matter in all modes.
16. What does
ElementNotInteractableExceptionusually mean?Correct answer: The element exists but is hidden, disabled or has no size
Common with hidden inputs behind custom controls. Interact with the visible control instead.
17. A sticky header covers the button the test clicks. What helps?
Correct answer: Scroll the element so it isn't under the header before clicking
scrollIntoView with block: 'center' or the Actions scroll API positions it in a free area.
18. How do you find a table cell next to a row label with XPath?
//td[text()='Total']/following-sibling::td[1]Correct answer: Use the following-sibling axis from the label cell
Axes like following-sibling, ancestor and preceding make XPath robust for tables and forms.
19. Which XPath handles a button whose id changes, like
save-8842?Correct answer:
//button[starts-with(@id, 'save-')]contains() and starts-with() match stable parts of dynamic attributes. Better still, ask for a stable test id.
20. Why does HTML5 drag and drop often fail with
Actions.dragAndDrop?Correct answer: Native HTML5 drag events aren't fired by synthetic moves
Workarounds: JS-triggered drag events or the app's alternative controls. Check browser-specific behavior.
21. How do you take a screenshot of just one element?
Correct answer: Call getScreenshotAs on the WebElement
Element screenshots are handy for visual diffs of components.
22. What are soft assertions good for in UI tests?
Correct answer: Collecting several checks and reporting all failures
TestNG SoftAssert or AssertJ SoftAssertions; call assertAll so failures are reported.
23. Why log in through the API and inject cookies instead of using the login form in every test?
Correct answer: It's faster and keeps tests focused on the feature under test
Cover the login UI in dedicated tests. Others start authenticated in seconds.
24. How do you set a value in localStorage from a test?
Correct answer: Run
localStorage.setItem(...)via executeScript on the domainStorage is per origin, so open a page of that domain first.
25. What should happen between tests that reuse the same browser?
Correct answer: Clear cookies and storage so state doesn't leak
deleteAllCookies plus clearing storage, or a fresh driver per test for strict isolation.
26. How do you test an infinite-scroll list?
Correct answer: Scroll, wait for new items to load and check the count grows
Assert on new items appearing, and stop on a known end marker or a maximum.
27. How should a test handle a custom date picker?
Correct answer: Use the widget like a user, or type into its input if supported
Setting hidden values bypasses validation and change events. Test the real interaction at least once.
28. What does
Select.isMultiple()tell you?Correct answer: Whether the select allows several options to be chosen
For multi-selects, deselectAll and getAllSelectedOptions are available.
29. How do you send Ctrl+A to an input?
new Actions(driver).keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();Correct answer: Use Actions with keyDown, sendKeys and keyUp
On macOS use Keys.COMMAND. Keys.chord(Keys.CONTROL, "a") is a shorter form with sendKeys.
30. Why add Allure steps and attachments to Selenium tests?
Correct answer: Reports show each step, with screenshots and logs
@Step on page methods and attachments on failure turn a red test into a readable story.
31. What is a risk of a TestNG retry analyzer for UI tests?
Correct answer: Real intermittent bugs get hidden behind green reruns
Track retried tests separately and fix causes. Retries buy time, not quality.
32. Why prefer explicit waits for a specific state over waiting for 'page load'?
Correct answer: SPAs keep loading after the load event; only the target state counts
Wait for what the next step needs: clickable button, loaded row, hidden spinner.
33. How do you wait until a loading spinner disappears?
Correct answer:
ExpectedConditions.invisibilityOfElementLocated(spinner)Then wait for the content you need. Spinners can flash too quickly to see first.
34. What is the main benefit of running Grid nodes in containers?
Correct answer: Clean, identical browser environments that scale up and down
Fresh containers avoid leftover profiles and crashed processes that make tests flaky.
35. What does
driver.manage().timeouts().scriptTimeout(...)control?Correct answer: How long asynchronous scripts from executeAsyncScript may run
pageLoadTimeout limits navigation, implicitlyWait limits element lookups.
36. How can Selenium 4 emulate a user's location?
Correct answer: Through CDP or BiDi commands for geolocation in supported browsers
Chromium-based browsers support it via DevTools; also grant the geolocation permission.
37. What changed for capabilities when moving from Selenium 3 to 4?
Correct answer: W3C-compliant capabilities replaced old JSON Wire ones like DesiredCapabilities
Use browser options classes. Vendor-specific settings go under keys like goog:chromeOptions.
38. What does Selenide's
shouldHave(text("Saved"))do?Correct answer: Waits until the element has the text, then passes or fails
Selenide conditions wait up to a timeout, which removes most explicit wait code.
39. How do you read all rows of an HTML table into a list?
Correct answer: findElements on the rows, then read cells per row
Map rows to objects for clean assertions; beware of rows rendered lazily on scroll.
40. Why do tests sometimes pass locally but fail in headless CI?
Correct answer: Different window size, fonts, timing or GPU change behavior
Set a fixed window size, use the same browser version and capture screenshots on failure.
41. What's a safe way to deal with a cookie-consent banner in tests?
Correct answer: Pre-set the consent cookie or close the banner in a shared setup
Banners intercept clicks. Handle them once, centrally, and test the banner itself separately.
42. How do you get the text of an input the user typed into?
Correct answer:
getDomProperty("value")orgetAttribute("value")getText returns visible text nodes. Inputs keep their content in the value property.
43. What's the risk of very long implicit waits in a suite?
Correct answer: Negative checks take the full timeout, slowing the suite a lot
Every 'element absent' check waits the whole time. Keep implicit at 0 and use explicit waits.
44. How do you test a site in a specific language with Chrome?
Correct answer: Set the browser's accept-language via options or prefs
Use --lang or intl.accept_languages prefs so the app's locale detection sees the right language.
45. Why should page methods not return raw
WebElements to tests?Correct answer: Tests then depend on the DOM and skip the page's waits
Return values (text, counts) or other page objects. Keep DOM details inside the page layer.
46. What is a good use of the
@BeforeMethodhook in TestNG UI tests?Correct answer: Creating a fresh driver and opening the start page for each test
Pair it with @AfterMethod(alwaysRun = true) to quit the driver even after failures.
47. Why does
alwaysRun = truematter on TestNG teardown methods?Correct answer: Teardown still runs if setup or a dependency failed
Without it, a failed @BeforeMethod can leave browsers open and break later tests.
48. How do you verify a link opens in a new tab without following it?
Correct answer: Check its target attribute or href rather than clicking
Link checks can be done on attributes; full navigation tests are for key flows.
49. What's a reasonable approach to visual checks in Selenium suites?
Correct answer: Use a visual diff tool on stable areas, with tolerances
Dynamic content, fonts and anti-aliasing make naive pixel diffs flaky. Mask changing regions.
50. How do you handle an HTML modal dialog (not a JS alert)?
Correct answer: Find its elements with normal locators and wait until visible
Only native alert, confirm and prompt need switchTo().alert(). HTML modals are part of the DOM.
51. Why should locators avoid CSS classes generated by build tools like
css-1x9k2?Correct answer: They change between builds and break locators
CSS-in-JS and modules generate hashed names. Use test ids or stable semantic attributes.
52. What does running tests on several browsers in Grid at once require?
Correct answer: Thread-safe drivers and tests that don't share data
Parallel cross-browser runs multiply any shared-state bug.
53. How do you test that a button becomes enabled after filling a form?
Correct answer: Wait for elementToBeClickable or check isEnabled
Assert state changes, not styling. Styling can change without behavior changing.
54. What does
driver.switchTo().newWindow(WindowType.TAB)do?Correct answer: Opens a new tab and switches the driver to it
Selenium 4 added it, so you don't need keyboard shortcuts to open tabs.
55. Why may tests in Firefox behave differently from Chrome for the same locator?
Correct answer: Browsers differ in rendering, events and timing
Cross-browser bugs are real: scroll behavior, focus, date inputs and file uploads often differ.
56. What is a good way to make a flaky UI test deterministic?
Correct answer: Find the race: wait for the right state, isolate data
Flakiness usually has a concrete cause. Fix it instead of hiding it.
57. How do you open a page with HTTP basic auth in Selenium 4 Chromium?
Correct answer: Register credentials via the BiDi or CDP auth handler
Credentials in the URL are blocked by modern browsers. The network auth handler responds to the challenge.
58. Why is reading the table text with one
getText()and splitting it fragile?Correct answer: Whitespace and line breaks vary by browser and layout
Read cell by cell. Parsing a blob breaks as soon as a cell contains a space.
59. What's the role of a base page class in a framework?
Correct answer: Shared helpers like waits and common components, kept small
Keep base classes thin; prefer components and helpers over a god class.
60. Why save page source and screenshots on every failure?
Correct answer: They show the state at the moment of failure for fast triage
Attach them in a listener so every failed test has evidence without reruns.
61. How do you check that a downloaded PDF has the right name?
Correct answer: Wait for the file in the download dir and check its name
Wait for the temp extension (.crdownload) to disappear before asserting.
62. What does
ExpectedConditions.frameToBeAvailableAndSwitchToItdo?Correct answer: Waits for the iframe and switches into it in one step
Useful when iframes load late, like payment widgets.
63. How do you handle nested iframes?
Correct answer: Switch frame by frame from the top, then defaultContent
You can't jump into a nested frame without entering its parents first.
64. Why prefer API calls for test data setup over UI steps?
Correct answer: Faster, more reliable setup; the UI test checks its feature
A test for 'edit order' shouldn't fail because 'create order' UI changed.
65. What is the trade-off of using Cucumber on top of Selenium?
Correct answer: Readable scenarios for business, but more glue code
It pays off when non-technical people read or write scenarios; otherwise it's overhead.
66. How do you test a tooltip that appears on hover?
Correct answer: Hover with Actions and wait for the tooltip to be visible
Custom tooltips are DOM elements; native title tooltips aren't visible to WebDriver.
67. What should happen to the driver when a test is interrupted by a timeout?
Correct answer: Teardown still quits it, or the session and browser leak
Orphaned sessions fill Grid slots and slow down later runs.
68. Why may
click()on a link in a hidden menu fail on mobile widths?Correct answer: The menu collapses and the link isn't visible until opened
Open the burger menu first, or set a desktop width when the test targets desktop.
69. What's a good naming practice for UI test methods?
Correct answer: Describe behavior, like userCanResetPasswordWithEmailLink
Clear names make reports readable and failures understandable without opening the code.
70. What does
ExpectedConditions.refreshed(...)help with?Correct answer: Re-finding an element after the DOM re-renders it
It wraps another condition and retries on stale references, useful for components that re-render.
71. Why keep the WebDriver version and the browser version in sync?
Correct answer: Mismatched versions cause session errors or odd behavior
Selenium Manager picks matching drivers; pin browser versions in CI for reproducible runs.
72. What is a good way to check text that loads with a delay?
Correct answer: Wait for textToBePresentInElement, then assert
Waiting for the expected text makes the check fast when ready and clear when it never comes.
73. How do you scroll to an element with the Selenium 4 Actions API?
Correct answer:
new Actions(driver).scrollToElement(el).perform()Selenium 4 added wheel actions: scrollToElement and scrollByAmount.
74. Why should a UI test framework capture the browser and driver versions in reports?
Correct answer: Failures can depend on versions; reports must show what ran
A test that fails only in Chrome 130 needs that fact recorded to be reproducible.
75. What does
getDomProperty("checked")return for a checkbox?Correct answer: The current checked state as a string, like true
Properties reflect live state; attributes reflect the HTML. isSelected() is the usual check.