Understanding the Difference between .keys and .setValue in WebDriver.io (JavaScript)

Understanding the Difference between .keys and .setValue in WebDriver.io (JavaScript)

In web automation testing, we often need to interact with input elements to enter data or test user interactions. WebDriver.io provides different methods to work with input elements, such as .keys and .setValue. In this article, we will explore the differences between these two methods and demonstrate how to use them effectively in a WebDriver.io test script.

Using .setValue to Set Input Field Values

The .setValue method allows you to set the value of an input field directly. This is a simple and efficient way to set the value of an input element when you don't need to simulate actual keystrokes. The following code snippet demonstrates how to use .setValue to set the value of an input field with an id locator.

const searchInput = await browser.$('#searchInput')
await searchInput.setValue("Hello World")

Here is an example test that uses the above code snippet.

See Working Example


Using .keys to Simulate Keystrokes in Input Fields

The .keys method is used to simulate actual keystrokes, which can be useful for testing user interactions or specific input behaviors. The following code snippet demonstrates how to use .keys to send a string of characters to an input field with an xpath locator.

const searchInput = await browser.$('#searchInput')
await searchInput.keys("Hello World")
await searchInput.keys("Enter")

Here is an example test that uses the above code snippet.

See Working Example


In summary, .setValue is best used when you need to set the value of an input field directly and efficiently, while .keys is suitable for simulating actual keystrokes and testing user interactions. Both methods have their own use cases, so it's important to choose the appropriate one based on your testing requirements.

Leave a reply

Your email address will not be published. Required fields are marked*

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.