Racing against Javascript
Welcome to the world where javascript is slower than C#. I hit a snag in intergration testing recently, where the test would fail all the time, but would pass when I tried to debug, and see where the problem was.
Turn out that I had a ModalPopupExtender on a link, that wasn't initialized by the time that I clicked the link. During debugging, it went slowly enough that the extender had time to initialize itself and work correctly when the test clicked the link. Reasonable thing to do, except that it never occured to me that this would happen after the page has finished loading, so I didn't consider it.
So, the problem is that I need to wait until some javascript is executed, and adds behavior to my element. I eneded up with this:
protected void WaitUntilBehaviorsHaveBeenDefined(Element element)
{
SimpleTimer timeoutTimer = new SimpleTimer(IE.Settings.WaitForCompleteTimeOut);
do
{
string result = Eval("Sys.UI.Behavior.getBehaviors(document.getElementById('" + element.Id + "')).length");
if (result != "0")
{
return;
}
Thread.Sleep(200);
} while (!timeoutTimer.Elapsed);
throw new TimeoutException(string.Format("waiting {0} seconds for behaviors to be defined on {1}.",
IE.Settings.WaitForCompleteTimeOut, element.Id));
}
And now this works perfectly. I was worried about using Sys.UI.Behavior, but it is interpreted before the page is finished loading, so that it guaranteed to work.
Comments
Comment preview