2

How can I test if an input field is infocus with protractor? I'm doing this:

it('should focus email field', function(){
    expect(element(by.model('login.email')).getAttribute('id')).toEqual(browser.driver.switchTo().activeElement().getAttribute('id'));
});

This seems to work with chrome, but this test fails with firefox. Any ideas?

This is the failure message:

[firefox #1]   2) Login page should focus email field
[firefox #1]    Message:
[firefox #1]      Expected 'login' to equal ''.
[firefox #1]    Stacktrace:
[firefox #1]      Error: Failed expectation
[firefox #1]     at [object Object].<anonymous> (/Users/Jason/Desktop/app/test/e2e/login-spec.js:38:69)
[firefox #1] 

Here's my test script:

describe('Login page', function() {
    var loginURL = 'http://localhost:8090/app/#/login';
    var loginEmailField = 'login-email';

    beforeEach(function() {
        browser.get(loginURL);
    });

    it('should focus email field', function(){     
        expect(element(by.id(loginEmailField)).getAttribute('id')).toEqual(browser.driver.switchTo().activeElement().getAttribute('id'));
    });
});
Jason
  • 1,787
  • 4
  • 29
  • 46

1 Answers1

2

You need to wait for angular before making any assertions:

beforeEach(function() {
    browser.get(loginURL);
    browser.waitForAngular();
});

Aside from that, this might be connected to the autofocus attribute, it has/had issues in Firefox, see:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Thanks for this. Good to know. But this doesn't fix the issue. Firefox still fails, while chrome doesn't fail. Strange. – Jason Jan 04 '15 at 19:55
  • Gives error - 'TypeError: Object [object Object] has no method 'activeElement'' – Jason Jan 04 '15 at 20:00
  • I should say, setting focus on the input field is done via a directive: Does this cause the issue? – Jason Jan 04 '15 at 20:01
  • @Jason yup, I think your last comment is a key to solving it. Looks like there are problems with `autofocus` on Firefox, see http://webmasters.stackexchange.com/questions/15020/why-doesnt-autofocus-autofocus-work-in-mozilla-firefox and http://stackoverflow.com/questions/9955398/autofocus-attribute-of-html5-does-not-work-only-in-firefox-when-forminput-ar. What firefox version are you using? – alecxe Jan 04 '15 at 20:03
  • Firefox version 34. Let me have a look at these links – Jason Jan 04 '15 at 20:04
  • Yep. This was it. I had written a directive for autofocus, but used it incorrectly. duh! – Jason Jan 04 '15 at 20:18