Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

A test clicks a 'Save' button that becomes enabled only after an async validation, and it fails randomly with ElementClickInterceptedException or NoSuchElementException. Rewrite the step with Selenium explicit waits and say which locator you would use.

The step fails randomly because it races the application: it tries to click Save before the async validation has finished, so the button is missing, still disabled or covered by a spinner. We fix it with an explicit wait, new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.elementToBeClickable(By.cssSelector("[data-testid=save]"))).click(), plus a wait for the overlay to disappear and a wait for the result of the save. For the locator, a stable data-testid or the button's accessible name is far better than a layout-based XPath.

Why this question is asked

Random failures like this are the main reason teams stop trusting their UI tests. The test is correct about what the user does; it is wrong about when. Interviewers ask this question because rewriting one step well shows that we understand synchronization in Selenium, the difference between implicit and explicit waits, and how locators affect stability. In this answer, we will recap what the two exceptions mean, look at the flaky step, rewrite it with explicit waits, choose a locator, wait for the outcome, and see why implicit waits and Thread.sleep make things worse.

1What the Two Exceptions Are Telling Us

NoSuchElementException means Selenium looked for the element at that moment and it was not in the page. With a single-page application, a button that appears only after validation may simply not exist yet when findElement runs.

ElementClickInterceptedException means the element exists, but when Selenium tried to click its centre, another element would have received the click. Typically that is a loading overlay or spinner placed on top of the form while validation runs. Selenium refuses to click through it, because a real user could not either.

Both errors have the same root cause: the test acts on the page while it is still changing. Whether the test passes depends on whether the validation request returned in 200 milliseconds or in 900, which is why it fails randomly.

2The Flaky Step

Here is the kind of step that produces both errors. It finds the button immediately after typing, and clicks it.

Java
driver.findElement(By.id("email")).sendKeys("ana@example.com");
driver.findElement(By.xpath("//div[3]/form/div[5]/button[2]")).click();
// fast validation: passes
// slow validation: NoSuchElementException (button not rendered yet)
// spinner on top: ElementClickInterceptedException (overlay receives the click)

Notice two separate problems. The step has no synchronization at all, and the locator depends on the exact layout of the page: the third div, the fifth div, the second button. Any change to the markup moves the button and breaks the test even when the timing is fine.

3Rewriting the Step With Explicit Waits

An explicit wait polls a condition until it becomes true or a timeout expires. WebDriverWait checks the condition every 500 milliseconds by default and returns the condition's result as soon as it is satisfied, so a fast page costs us almost nothing and a slow page gets up to the full timeout.

ExpectedConditions.elementToBeClickable(locator) waits until the element is present, visible and enabled, and returns the element. But there is a catch: it does not check whether something is covering the element. So when the application shows an overlay during validation, we first wait for that overlay to disappear.

Java
By save = By.cssSelector("[data-testid=save]");
By spinner = By.cssSelector("[data-testid=validation-spinner]");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
driver.findElement(By.id("email")).sendKeys("ana@example.com");
wait.until(ExpectedConditions.invisibilityOfElementLocated(spinner)); // true once the overlay is gone
wait.until(ExpectedConditions.elementToBeClickable(save)).click(); // present, visible and enabled
// slow validation (900 ms): waits about 900 ms, then clicks; no exception
Step throughWhat the rewritten step does
  1. Type the emailasync validation starts, spinner appears
  2. Spinner still visible?
    YesPoll again in 500 msNoContinue
  3. Save present, visible and enabled?
    YesClick SaveNoPoll again until 10 s
  4. Wait for the confirmationvisibilityOfElementLocated on the success message
  5. Assert in the testthe message text and the saved data

5 steps in order. Play them, or step through them one at a time.

Each wait is on a state of the application, not on a fixed amount of time.

So the step now says what a user does: wait until validation is finished and Save can be pressed, then press it. If validation never finishes, the wait fails after 10 seconds with a TimeoutException that names the condition, which is a much clearer failure than a random interception.

4Choosing the Locator

A good locator survives changes that do not matter to the user. A data-testid attribute, an attribute the front-end team adds only for tests, is the most stable choice: it does not change when the layout, the styling or the text changes. We agree it with the developers, and it becomes part of the component's contract.

The second good choice is the element's accessible name and role, for example the button whose visible label is Save. That also checks something a user cares about, and it encourages accessible markup. Selenium can find by visible text with an XPath such as //button[normalize-space()='Save'], which is fine because it does not depend on position.

What we avoid are positional XPath expressions like the one in the flaky step, and generated class names such as css-1x2y3z, which many CSS-in-JS libraries change on every build.

5Waiting for the Result, Not Just the Click

A click only starts the save. If the test's next line immediately checks the result or navigates away, it races the save request in the same way the click raced the validation. So the step should also wait for the outcome: a confirmation message becoming visible, or the spinner disappearing again, or the button text changing.

Java
By savedMessage = By.cssSelector("[data-testid=save-confirmation]");
WebElement message = wait.until(ExpectedConditions.visibilityOfElementLocated(savedMessage));
assertEquals("Changes saved", message.getText()); // passes once the request has completed

Notice that the assertion belongs in the test, while the waits can live in a page object method such as saveChanges(), so that every test that saves gets the same safe behaviour.

6Why Not Implicit Waits or Thread.sleep

An implicit wait, set once with driver.manage().timeouts().implicitlyWait(...), makes every findElement retry until the element is present. It sounds convenient, but it only knows about presence, not visibility, enabled state or overlays. Worse, when it is combined with explicit waits, the two timeouts interact: each poll inside the explicit wait may itself block for the implicit timeout, so a 10 second explicit wait with a 10 second implicit wait can take far longer, or fail at surprising times. The Selenium documentation warns against mixing them, so we set the implicit wait to zero and use explicit waits only.

Thread.sleep(2000) is the worst option. It waits two seconds every time, even when the page was ready after 100 milliseconds, so a suite with hundreds of sleeps becomes slow. And it is still flaky, because on a busy CI agent validation sometimes takes 2.5 seconds. A sleep guesses; an explicit wait checks.

7Follow-up questions

How would you wait for an element's text to change?

If we know the expected text, ExpectedConditions.textToBe(locator, "Saved") or textToBePresentInElementLocated(locator, "Saved") waits for it. If we only know the old value, we can capture it and wait with a lambda: String before = driver.findElement(status).getText(); wait.until(d -> !d.findElement(status).getText().equals(before)). The lambda finds the element again on each poll, so it also survives a re-render that replaces the node.

What timeout should an explicit wait use?

Long enough for the slowest realistic case on CI, short enough that a real failure is reported quickly. Ten seconds is a common default for UI actions. We keep it in one place, a shared wait helper or base page object, so we can tune it for the whole suite rather than scattering numbers through tests.

Can we just catch ElementClickInterceptedException and retry the click?

That hides the cause and can click at the wrong moment, for example while validation is still running. It is better to wait for the condition that makes the click safe, such as the overlay being gone, and let a timeout report clearly when that condition never arrives.

8Conclusion

In this answer, we saw that NoSuchElementException and ElementClickInterceptedException in this step both come from acting before the asynchronous validation finished. We rewrote the step with WebDriverWait: first waiting for the spinner to become invisible, then waiting for the Save button to be clickable, then waiting for the confirmation after the click. We chose a data-testid or accessible name instead of positional XPath, and we avoided implicit waits mixed with explicit ones and Thread.sleep, because both make timing unpredictable.

What to say in the interviewAbout 90 seconds aloud

Open with

Both exceptions come from the test racing the page. NoSuchElement means the button was not rendered yet when findElement ran, and ElementClickIntercepted means it was there but a spinner or overlay was on top, so the click would land on that instead.

Then, if they want more

I would rewrite the step with explicit waits on application states. I create a WebDriverWait with a ten second timeout, wait for the validation spinner to become invisible, then call wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("[data-testid=save]"))).click(). I wait for the spinner separately because elementToBeClickable only checks that the element is visible and enabled; it does not notice something covering it.

After the click I also wait for the result, for example visibilityOfElementLocated on the confirmation message, and then assert its text in the test. For the locator I would use a data-testid agreed with the front-end team, or the button's accessible name, rather than a positional XPath or generated class names, which break whenever the markup changes.

I keep the implicit wait at zero, because mixing implicit and explicit waits makes the real timeouts unpredictable, and I never use Thread.sleep, which is slow when the page is fast and still flaky when CI is slow.

I would put these waits inside a page object method like saveChanges so every test gets the same behaviour, and to wait for text to change I would use textToBe or a lambda that re-reads the element.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A test clicks a 'Save' button that becomes enabled only after an async validation, and...": https://scrivio-interview-library.netlify.app/java/ui-testing/f3c37cf84a/