Testing focus/blur events with Cucumber

Updated . Posted . Visible to the public.

This is a problem when using Selenium with Firefox. We recommend using ChromeDriver for your Selenium tests.


This setup allows to test focus/blur events in Cucumber tests (using Selenium). For background information, see How to solve Selenium focus issues.

Cucumber step definition:

# This step is needed because in Selenium tests, blur events are not triggered
# when the browser has no focus.
When /^I unfocus the "(.*?)" field to trigger javascript listeners$/ do |field_label|
  field = page.find_field(field_label)

  # Firing 'autocomplete:done' is a workaround to trigger on-blur listeners on
  # the element. However, this does not remove focus from a field. If the
  # browser has focus during a test run, the browser will trigger real blur
  # events which will trigger the listeners a second time.
  #
  # To prevent this, we also blur the field and then wait for the listeners to
  # finish their work.
  page.execute_script <<-JS
    field = $('#{field[:id]}')
    field.blur()
    field.fire('autocomplete:done')
  JS
  sleep 1
end

In the javascript:

 /*
   * Listening on "blur" events does not work in tests because Firefox has a bug
   * deferring focus/blur events until the window has focus:
   * https://bugzilla.mozilla.org/show_bug.cgi?id=566671
   * Cure: Have the "blur" event trigger a custom event which can be manually
   * triggered in tests.
   */
  $('invoice_template_company').observe('blur', function() {
    this.fire('autocomplete:done');
  });
  $('invoice_template_company').observe('autocomplete:done', doSomething);
Dominik Schöler
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2015-01-13 15:59)