Back to Challenges
The Wrong Tab
intermediate Python 10 minA test that opens a help link in a new tab sometimes asserts against the original tab. Fix the handle logic.
The Scenario
The Help centre link has target="_blank". The test switches to “the last handle”, which is usually the new tab but not always: sometimes the click has not opened it yet, so the last handle is still the original tab. Then, after closing what it thinks is the new tab, the next command throws NoSuchWindowException.
Your Task
Make the tab handling deterministic: wait for the new tab, identify it without relying on order, assert in it, close it, and return to the original tab.
What Good Looks Like
- The handle set is captured before the click and diffed after.
- A wait covers the gap between click and tab creation.
- The driver is switched back to the original handle before further commands.
Your task
A test that opens a help link in a new tab sometimes asserts against the original tab. Fix the handle logic.
Problem Code
def test_help_opens_in_new_tab(driver):
driver.get("https://app.example.com/settings")
driver.find_element(By.LINK_TEXT, "Help centre").click()
driver.switch_to.window(driver.window_handles[-1])
assert "Help" in driver.title # sometimes fails: title is "Settings"
driver.close()
driver.find_element(By.ID, "save").click() # NoSuchWindowException when it gets here
Need Help?
Solution
Try to solve the challenge yourself before revealing the solution.