WatiN – How to simulate tabbing

Tricks to simulate tabbing on IE using WatiN framework

Citation
, XML
Authors

Abstract

I spend a few hours to work out how to simuate tabbing using WatiN framework. I thought it was worth sharing as it may come handyin testing the tabbing order of your web app.
Answer to “WatiN PressTab doesn’t press tab”

1. Make sure you have got these PInvokes in your test class:
[DllImport("user32.dll")]
[returnMarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
static extern IntPtr SetFocus(IntPtr hWnd);
2. Assuming you start with a text field in yout test method:
IE iExplorer = new IE(SelfServiceUrl);
 
TextField tfUserName = iExplorer.TextField(_TF_UserName);
Assert.IsTrue(tfUserName.Exists, "UserName text field not found");
 
Get the ref of the next field in the ideal tab order:
TextField tfPassword = iExplorer.TextField(_TF_Password);
Assert.IsTrue(tfPassword.Exists, "Password text field not found");
 
// Set the foreground window and focus using PInvoke
SetForegroundWindow(iExplorer.hWnd);
SetFocus(iExplorer.hWnd);
 
//Simulate typing the user name field to get focus on that field
tfUserName.TypeText("Rio"); //Rio is my son's name, use any word you like 🙂
 
//Simulate tabbing
//Some people suggest System.Windows.Forms.SendKeys.SendWait("{TAB}"); but I didn't need that

iExplorer.PressTab();
iExplorer.WaitForComplete();
 
// Check if the tabbing was in the right order
if (iExplorer.ActiveElement.Name != tfPassword.Name)
{
      iExplorer.Close();
      Assert.IsTrue(false"Tab order after user name textfield incorrent");
}
//Now carry on with further tab tests
 

Hope that works for you!