Scotty Bollinger
Scotty Bollinger

Reputation: 2363

JavaScript Protractor (Selenium) verify if input is focused

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?

Upvotes: 4

Views: 6389

Answers (2)

cjsimon
cjsimon

Reputation: 1221

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]);
});

Upvotes: 0

glepretre
glepretre

Reputation: 8167

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'));
});

Upvotes: 9

Related Questions