Sunday, February 27, 2011

WatiN – How to handle confirmation window

This example will illustrate how to handle confirmation window from web page. For example, web page generate confirmation message, when user wants to delete a records and click “Delete” button. Web page includes some javascript like the following:
javascript:{if (confirm('Confirm that you want to delete this record.'));}

For click OK button on the message and continue test we need to add following ConfirmDialogHandler():
var alertDialogHandler = new ConfirmDialogHandler();
using (new UseDialogOnce(_browser.DialogWatcher,
                         alertDialogHandler))
{
    myPage.DeleteButton.ClickNoWait();
    alertDialogHandler.WaitUntilExists();
    alertDialogHandler.OKButton.Click();
}
I guess, that the most tricky part of this code is the ClickNoWait(). Usually when I need to click on any button during the test I use Click() method. But in case we are looking for confirmation or alert window after button was clicked, we should use ClickNoWait().

Let see what is the difference between these two methods:
public virtual void Click()
{
    if (!this.Enabled)
    {
        throw new ElementDisabledException(this.IdOrName, this);
    }
    Logger.LogAction("Clicking {0} '{1}', {2}", new object[] { base.GetType().Name, this.IdOrName, base.Description });
    this.Highlight(true);
    this.NativeElement.ClickOnElement();
    try
    {
        this.WaitForComplete();
    }
    finally
    {
        this.Highlight(false);
    }
}

public virtual void ClickNoWait()
{
    if (!this.Enabled)
    {
        throw new ElementDisabledException(this.IdOrName, this);
    }
    Logger.LogAction("Clicking (no wait) {0} '{1}', {2}", new object[] { base.GetType().Name, this.IdOrName, base.Description });
    this.Highlight(true);
    INativeElement nativeElement = this.NativeElement;
    UtilityClass.AsyncActionOnBrowser(new ThreadStart(nativeElement.ClickOnElement));
    this.Highlight(false);
}
In the method ClickNoWait() the new thread is launched and click method is executed in it. As result, using this method we can continue without waiting for the click event to be finished. Due to this, confirmation window become available for user actions.

1 comment: