How to test whether an input form field is focussed?

1.8k views Asked by At

For the following sign-up form I configured that the first input field with id="signUpName" is focused when the form is rendered. Backbone-forms is used to create the form.

Sign-in form

I want to test with Jasmine v.1.3.0 whether a certain input form field is focussed when I load a view:

it("should focus the name field of the sign-up form", function() {
  var signUpName = userController.loginView.signUpForm.$el.find("#signUpName");
  userController.loginView.showSignUpForm();
  expect(signUpName).toBeFocused();
  // expect(signUpName.is(":focus")).toBe(true);
});

Jasmine prompts:

Expected '<input id="signUpName" name="signUpName" type="text">' to be focused.

As you can see from the spec I use the toBeFocused() matcher from jasmine-jquery. I run the latest version 1.5.93 of the extension. I also found the discussion on the implementation of toBeFocused() and noticed that they meanwhile changed it to the alternative implementation suggested by Ryan Greenberg.

As an alternative I tried to spy on the focus event - if there actually is one?

it("should focus the name field of the sign-up form", function() {
  var signUpName = userController.loginView.signUpForm.$el.find("#signUpName");
  var spyEvent = spyOnEvent(signUpName, 'focus');
  userController.loginView.showSignUpForm();;
  expect('focus').toHaveBeenTriggeredOn(signUpName);
  expect(spyEvent).toHaveBeenTriggered();
});

Jasmine prompts:

Expected event focus to have been triggered on [object Object]
1

There are 1 answers

0
Gojko Adzic On

We ran into a similar problem on MindMup, where the issue was that focus wasn't triggered on that particular object, but on a different jQuery selector that matched that object. We wrote a few matchers for Jasmine that check if the event was actually triggered on a equivalent jQuery set of DOM elements. See https://github.com/mindmup/mapjs/blob/master/test-lib/jquery-extension-matchers.js

With that, you can do:

spyOn(jQuery.fn, 'focus').and.callThrough();
// your test
expect(jQuery.fn.focus).toHaveBeenCalledOnJQueryObject(yourObject);