Skip to main content

How to Test Dynamic Pages

Intro​

This tip will go over how to implement explicit waits for testing dynamic web pages.

Let's say you want to test some functionality of a web application, but it loads things dynamically. You might think about using a hard-coded sleep (that you constantly tweak due to test failures) or you use a blanket timeout (like an Implicit Wait) that you likely bump up to address test instabilities as well.

This may work in the short term, but your tests are now slower and leaving you (and your team) feeling like your test automation is on shaky ground -- uncertain of when the next break/fix cycle will happen.

A Solution​

By using a flexible wait strategy you can easily meet the rigors of testing dynamic web applications.

Thankfully Selenium comes with one built in -- Explicit Waits. With them, you specify a timeout and an action. Selenium will repeatedly try that action until it can either complete it successfully (at which point it will move onto the next step of the test), or it will throw a timeout exception (causing your test to error).

Let's continue with an example.

Example​

Let's use an example from the-internet which loads content dynamically. On it there is a Start button that when clicked will trigger a loading bar to appear for 5 seconds. After that time it will disappear and an element with the text Hello World! will appear.

There are two variations of the page, and we test both of them:

  • Example 1: the element is already on the page, but hidden.
  • Example 2: the element is rendered after the loading finishes.

In each test we visit the page, click the start button, wait for the finish text to be displayed, and assert that it is displayed. Rather than litter our test code with the verbose Selenium incantation, we pull the explicit wait out into a small helper that accepts the condition to wait for and a timeout (10 seconds by default).

If we set the timeout too low (e.g., 2 seconds) Selenium won't wait long enough for the loading bar to finish, which will trigger the timeout threshold and throw a timeout exception. And if we didn't use an explicit wait at all, the test would fail because Selenium would try to check for the finish text before it is displayed (e.g., a NoSuchElement error in the second example).

Expected Behavior​

  • Open the browser
  • Visit the page
  • Click the Start button
  • Wait for the loading bar to disappear and display the finish text
  • Assert that the finish text element is displayed
  • Close the browser

Summary​

Hopefully this tip will help you build more efficient and resilient tests when faced with dynamic pages that are constructed in various ways.

Happy Testing!

Authors​

Dave Piacente
Original creator of Elemental Selenium
Diego Molina
Elemental Selenium maintainer