4

I'm trying to to test whether an element is focused using selenium webdriver in protractor. This is before AngularJS is loaded so I am having to use the driver as seen here:

var ptor = protractor.getInstance(),
    driver = ptor.driver;

I also need to know how to make the test wait until the input is focused. I have to wait until a model is fired so the input is not focused for half a second as seen here:

window.setTimeout(function(){
  $("input#email").focus();
}, 500);

Any idea how to verify if an input has focus after 500ms?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Scotty Bollinger
  • 2,343
  • 4
  • 19
  • 25
  • Possible duplicate of [How do I assert an element is focused?](http://stackoverflow.com/questions/22753496/how-do-i-assert-an-element-is-focused) – Keith Oct 15 '15 at 18:25

2 Answers2

9

Based on my answer to this question, and adapting it to your case, it would look like:

it('should focus on foo input', function () {
    // to wait 500ms+
    browser.driver.sleep(600);

    // using the Protractor 'element' helper
    // https://github.com/angular/protractor/blob/master/docs/api.md#element
    // var input = element(by.id('foo'));

    // using findElement with protractor instance
    var input = driver.findElement(protractor.By.id('foo'));

    expect(input.getAttribute('id')).toEqual(browser.driver.switchTo().activeElement().getAttribute('id'));
});
Community
  • 1
  • 1
glepretre
  • 8,154
  • 5
  • 43
  • 57
  • This got it. Thanks! There is a bit of a difference in syntax for the getting element by ID and the second to last line needs an extra parenthesis but other than that it worked like a charm. Adding another answer below with the correct syntax and parentheses below. Thanks again!! – Scotty Bollinger Mar 31 '14 at 15:07
  • You're right, I edited my answer to fix this missing parenthesis ;) And I guess the short `element(by.id())` syntax did not work for you because angular is not loaded in your case? – glepretre Mar 31 '14 at 15:32
  • That's correct. In my use case, the login modal is fired on the marketing site, which is outside of Angular. Thanks again! – Scotty Bollinger Mar 31 '14 at 16:16
  • assertionError: expected { Object (browser_, then, ...) } to equal { Object (flow_, stack_, ...) } – cjsimon Jun 27 '17 at 23:30
0

I used glepretre's answer, but had to resolve the getAttribute promises for both elements using promise.all

let activeElement = browser.driver.switchTo().activeElement().getAttribute('id');
let compareElement = element(by.id('your-element-id')).getAttribute('id'); 
webdriver.promise.all([compareElement, activeElement]).then((id) => {
    expect(id[0]).to.equal(id[1]);
});
cjsimon
  • 1,121
  • 12
  • 22