Thread.Sleep() is a big hammer : How to wait for elements in WebDriver?

One of the most common elements that drives failures in unit test that works with browser automation is the fact that at the time of performing evaluations or assertions, those elements are either unavailable or the text that has not been rendered. WebDriver in particular, throws an exception when the HTML element does not exist.

I’ve seen son scenarios when WebDriver throws an exception because at the time of accessing those elements, there were some other task running in the background  so you have a really difficult situation (it gets complicated because if you run that test in debug mode it works fine).

Therefore is required to find a way to wait for elements. Thread.Sleep() can do the job, because what you are looking for is a way to wait some time until the elements you need to pass the test are available.

Thread.Sleep blocks the current thread for the specified number of milliseconds.But how long time is good enough?. 

If you use this method you are forcing yourself to wait for an amount of milliseconds and there is no way to be sure that your elements are going to be ready in more or less time than the specified in the sleep method.

What can we do to know when an element is “ready”?

Well I’ve found fairly easy to create a function that returns a boolean if the element I’m trying to find is : visible and has some text.

If the element is not visible, then there is a wait implementation that breaks the waiting time once it meets the spectations (the element is visible for instance),

The following piece of code is very useful for this kind of scenarios:


 It seems like some browsers rendered the content faster than others, so it is good to do an evaluation before trying to use the html elements.


About Michael Hidalgo

Michael is a Software Developer Engineer based on San José, Costa Rica. He leads the OWASP Chapter from Costa Rica. You can take a look at my blog at
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

One Response to Thread.Sleep() is a big hammer : How to wait for elements in WebDriver?

  1. Pingback: A new way to deal with Ajax events and avoid the usage of Thread.Sleep() | TeamMentor Development and Testing

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s