Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to use Actions.sendKeys() or WebElement.sendKeys() to simulate a user typing with Selenium WebDriver?

As far as I'm aware there are two ways of typing with Selenium:

new Actions(webDriver).sendKeys("text to send").perform();
webElement.sendKeys("text to send");

The Actions method seems like the most natural way of replicating a user typing as the keys are sent wherever the browser wants (I believe a method called sendKeysToActiveElement is being used under the covers). However, many tutorials instruct testers to use the WebElement method (this is in fact the only option when using SafariDriver), I assume as it is simpler.

Is the Actions method actually a better simulation of user interaction, or should I use the WebElement method for convenience?

like image 546
Dave Avatar asked Mar 15 '23 17:03

Dave


2 Answers

public Actions sendKeys(java.lang.CharSequence... keys)

Sends keys to the active element. This differs from calling WebElement.sendKeys(CharSequence...) on the active element in two ways:

  1. The modifier keys included in this call are not released.
  2. There is no attempt to re-focus the element - so sendKeys(Keys.TAB) for switching elements should work.

for more you can refer this link : https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/interactions/Actions.html#sendKeys-java.lang.CharSequence...-

like image 108
cruisepandey Avatar answered Apr 09 '23 15:04

cruisepandey


This doesn't answert the question directly but I would have thought using SendKeys in the WebElement class would have been better, since you already have the WebElement object in memory, why do you need to create an Actions object?

I have always used the WebElement.SendKeys() method and I have not found any uses to switch over to using the Actions class for sending over a regular string.

I would use the Actions class when I require more complex scenarios e.g. Need to hold down a button or drag something.

like image 21
Jamie Rees Avatar answered Apr 09 '23 14:04

Jamie Rees