Wednesday 19 June 2013

Automated UI WatiN Test - JavaScript Keyup event not firing

While writing UI test case for textbox validator I came across a problem that JavaScript key up event is not firing. Below extension method  “ForceKeyUpEvent”  helps to fire JavaScript event.
using System;
using WatiN.Core;

namespace Twenty57.Stadium.TestHelpers.WatiNElements
{
       public static class WatiNExtensions
       {
              public static void ForceKeyUpEvent(this Element e)
              {
                     e.DomContainer.Eval("$('#" + e.Id + "').keyup();");
              }
       }
}

[Test]
              public void TestAmountValidator()
              {
                     string validatorControlID = "Page1_AmountTextBox";
                     string validatorMessage = "Please enter a valid amount";

                     this.browser.GoTo(this.appURL + "/Page1");
                     this.browser.WaitForComplete();

                     TextField textbox = this.browser.TextField(Find.ById(validatorControlID));
                     Assert.IsNotNull(textbox, string.Format("Validator textbox with Id [{0}] not found.", validatorControlID));
                     textbox.TypeText("Amount Validator");
                     textbox.ForceKeyUpEvent();
                     this.browser.WaitForComplete();

                     string errorspanId = validatorControlID + "_Error";
                     Span errorspan = this.browser.Span(Find.ById(errorspanId));
                     Assert.IsNotNull(errorspan, string.Format("Validator error span with Id [{0}] not found.", errorspanId));
                     if (validatorMessage == null)
                     {
                           Assert.AreEqual("none", errorspan.Style.Display, "Validation message display is not correct.");
                     }
                     else
                     {
                           Assert.AreEqual("inline", errorspan.Style.Display, "Validation message display is not correct.");
                           Assert.AreEqual(validatorMessage, errorspan.Text, "Validator message is not correct.");
                     }

              }

1 comment:

  1. As of Windows 8.1 I started receiving errors when repeatedly calling the above ForceKeyUpEvent. The eval event would throw an exception stating:

    "Unable to cast object of type 'System.DBNull' to type 'System.String'

    This was resolved by simply using the RunScript method instead of the Eval method:

    public static void ForceKeyUpEvent(this Element e)
    {
    e.DomContainer.RunScript("$('#" + e.Id + "').keyup();");
    }

    ReplyDelete