Search code examples
javaseleniumvisibilitysleepwebdriverwait

How to dynamically check table is available ("waiting") using Selenium instead of having a fixed sleep


Code block:

private void SelectRows()
{
  var wait = new WebDriverWait(Driver, TimeSpan.FromMilliseconds(500);

  // enabling the Rows
  this.Page.EnableRowsButton.Click();
  wait.Until(_ => this.Page.EnableRowsButton.Checked);

  // Sleeping to ensure row exists; I want to use here WebDriverWait so it's faster
  Thread.Sleep(500);

  // Row modification
  foreach (Table.Row row in this.Page.MyTable.Content.Rows)
  {
    // do stuff
    row.CellAt(0).Find<Checkbox>().Click();
  }  
}

The issue I have is with Thread.Sleep(500); I am doing this a lot and the time adds up. If I choose it too high my tests run more stable but takes longer to test. If I do it too short my test tends to fail since it wasn't loaded properly.

I want to use WebDriverWait (see in code):

wait.Until(_ => this.Page.EnableRowsButton.Checked);

instead of Thread.Sleep() to see the Rows are loaded completely.

WebDriverWait wait until it becomes available. So I can choose a bigger duration and it will be shorter if it is sooner available.

Any suggestions?


Solution

  • With the following instance of WebDriverWait:

    var wait = new WebDriverWait(Driver, TimeSpan.FromMilliseconds(500);
    

    Once you click and enable the rows, to wait for the rows to exist there can be two approaches:

    • As there is some ambiguity regarding the number of rows (no row, 1 row or multiple rows), a safer approach would be to probe the Displayedness of the MyTable element as you mentioned in your comment. The element displayed algorithm is a boolean state where true signifies that the element is displayed and false signifies that the element is not displayed.

      TcAssert.WaitUntilTrue(() => this.Page.MyTable.Displayed);
      
    • The other approach would be to wait for the Visibility of the element MyTable. The visibility of an element is guided by what is perceptually visible to the human eye. and is based on crude approximations about an element's nature and relationship in the tree. An element is in general to be considered visible if any part of it is drawn on the canvas within the boundaries of the viewport.