I do not know if this was what you expect, but I had time to study, and I came up with a solution to the question: with WatiN, I would like to wait for the jQuery event.
The goal is to write in C #:
Browser.WaitForEvent("#link", "onclick");
I wrote a test page (available at http://www.sp4ce.net/debug.html ), where it triggers the onclick event in the link when you click on the button.
Then I wrote an extension method .WaitForEvent
public static void WaitForEvent(this Browser browser, string selector, string eventname) { using (EventMonitorWatcher monitor = new EventMonitorWatcher(browser, selector, eventname)) { int timeWaited = 0; var maxTimeWait = Settings.WaitForCompleteTimeOut * 1000; do { Thread.Sleep(Settings.SleepTime); timeWaited += Settings.SleepTime; } while (!monitor.IsEventCalled() && timeWaited < maxTimeWait); } }
This method uses an EventMonitorWatcher , the verification of which is triggered by an event.
public class EventMonitorWatcher : IDisposable { private readonly Browser _browser; private readonly string _selector; private readonly string _eventname; public EventMonitorWatcher(Browser browser, string selector, string eventname) { _browser = browser; _selector = selector; _eventname = eventname; _browser.Eval(string.Format("startEventMonitor('{0}', '{1}')", _selector, _eventname)); } public bool IsEventCalled() { string result = _browser.Eval(string.Format( "isEventCalled('{0}', '{1}')", _selector, _eventname)); return result == "true"; } public void Dispose() { _browser.Eval(string.Format("stopEventMonitor('{0}', '{1}')", _selector, _eventname)); } }
This monitor uses three javascript (jquery powered) methods that start monitoring, stop monitoring and check if an event has been triggered.
startEventMonitor = function(selector, event) { $(selector).data('eventMonitorResult', false); var eventMonitorHandler = function() { $(selector).data('eventMonitorResult', true) }; $(selector).data('eventMonitorHandler', eventMonitorHandler); $(selector).bind(event, eventMonitorHandler); }; stopEventMonitor = function(selector, event) { $(selector).undbind(event, $(selector).data('eventMonitorHandler')); $(selector).data('eventMonitorResult', false); }; isEventCalled = function(selector, event) { return $(selector).data('eventMonitorResult'); };
Here you are, then you need to enter this javascript as a line of your page when the browser starts.
[Test] public void Test() { using(var browser = new IE("http://www.sp4ce.net/debug.html") { browser.Eval(JavaScript); browser.WaitForEvent("#link", "onclick"); } }
In this test, when you click the "click" button, the test should end directly and your browser will close;