In UI Testing, sometimes you are limited by how fast the UI can process each request or page load. Your tests may have trouble finding UI elements just simply because they haven’t had a chance to load yet. To combat this issue, we need to introduce the “Wait For Element” concept.
In Xamarin.UITest, it is built right into the App class, which we can make use of. An example usage can be seen below:
app.WaitForElement(e => e.Marked(<item>), <timeoutMessage>, TimeSpan.FromSeconds(<timeInSeconds>));
This is great and all, but wouldn’t it get tedious to repeat this every time you needed to wait on something to appear? Why don’t we make things much easier for us by extending the App class with the following method:
public static void WaitUntilElementIsVisible(this IApp app, string markedId, int timeInSeconds = 3)
{
var timeoutMessage = $"UI Test timed out while waiting on {markedId} to appear. (Total wait time: {timeInSeconds} seconds)";
app.WaitForElement(e => e.Marked(markedId), timeoutMessage, TimeSpan.FromSeconds(timeInSeconds));
}
Now, you can just simply call WaitUntilElementIsVisible() on the App object and passing in the Marked Id, with the optional timeout which defaults at 3 seconds.
Example usages:
app.WaitUntilElementIsVisible("SomeLabelId"); // Default of 3 second timeout
app.WaitUntilElementIsVisible("SomeLabelId", 10); // 10 second timeout