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.