How to test whether an input form field is focussed?

Viewed 1761

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 Answers
Related