Selenium Scripting & Execution Processes 2 — Questions and Answers
Question 1: Which method in Selenium WebDriver is used to execute JavaScript code directly in the browser?
- driver.runScript()
- driver.executeScript() (Correct answer)
- driver.eval()
- driver.jsRun()
Correct answer: driver.executeScript()
JavascriptExecutor's executeScript() method allows direct execution of JavaScript in the browser context.
Question 2: What is the correct way to handle a browser alert using Selenium WebDriver?
- driver.getAlert().accept()
- driver.switchTo().alert().accept() (Correct answer)
- driver.alert().dismiss()
- driver.handleAlert().accept()
Correct answer: driver.switchTo().alert().accept()
driver.switchTo().alert() switches context to the alert, then accept() or dismiss() handles it.
Question 3: In a TestNG Selenium test, which annotation runs a method once before all tests in a class?
- @BeforeMethod
- @BeforeTest
- @BeforeClass (Correct answer)
- @BeforeSuite
Correct answer: @BeforeClass
@BeforeClass runs exactly once before the first test method in the current class is invoked.
Question 4: How do you scroll to a specific element using Selenium's Actions class?
- actions.scrollToElement(element).perform()
- actions.moveToElement(element).perform() (Correct answer)
- actions.scroll(element).perform()
- actions.focus(element).perform()
Correct answer: actions.moveToElement(element).perform()
actions.moveToElement(element).perform() scrolls the element into view and moves the mouse to it.
Question 5: What does the Selenium Grid hub do in a distributed test execution setup?
- Runs test scripts directly on browsers
- Receives test requests and routes them to registered nodes (Correct answer)
- Stores test results in a database
- Generates test reports automatically
Correct answer: Receives test requests and routes them to registered nodes
The hub acts as a central router that receives test session requests and delegates them to available nodes.
Question 6: Which WebDriverWait condition checks that an element is present in the DOM and visible?
- ExpectedConditions.elementExists()
- ExpectedConditions.visibilityOfElementLocated() (Correct answer)
- ExpectedConditions.elementPresent()
- ExpectedConditions.elementDisplayed()
Correct answer: ExpectedConditions.visibilityOfElementLocated()
visibilityOfElementLocated() waits until the element is present in the DOM and has non-zero dimensions.
Question 7: When running parallel tests with TestNG and Selenium Grid, what attribute in testng.xml enables parallel execution at the method level?
- parallel="tests"
- parallel="classes"
- parallel="methods" (Correct answer)
- parallel="instances"
Correct answer: parallel="methods"
Setting parallel="methods" in the suite tag causes each test method to run in a separate thread concurrently.
Which method in Selenium WebDriver is used to execute JavaScript code directly in the browser?