How do I assert an element is focused?

谁说胖子不能爱 提交于 2019-12-28 13:21:10

问题


I am attempting to verify that the focused element is set on page load as one of my tests.

This seems to be working, and I can verify with the element explorer, but the Jasmine matchers don't seem to pick up on this.

Here's my code:

var LoginPage = function () {
    this.basePath = browser.params.baseUrl;
    this.loginPart = "/#/login";
    this.usernameInput = element(by.model('username'));

    this.get = function () { ... }
}

it('should focus on the username field on load', function () {
     loginPage.get();
     expect(loginPage.usernameInput).toBe(browser.driver.switchTo().activeElement());
});

The field itself is correctly getting focus when the page loads (and element explorer correctly allows me to query this via browser.driver.switchTo().activeElement(), so I think this test should be passing, but it isn't.

Instead I get an enormous stacktrace which doesn't offer any useful information.


回答1:


I think I found a workaround:

Since expect expects to be called with a promise, you can compare some attribute of the two webElements (your input and the currently activeElement) :

it('should focus on the username field on load', function () {
     loginPage.get();
     expect(loginPage.usernameInput.getAttribute('id')).toEqual(browser.driver.switchTo().activeElement().getAttribute('id'));
});



回答2:


I ended up using this nice simple function to assert focus.

var expectToBeFocused = function(element){
  return expect(element.getInnerHtml()).
    toBe(browser.driver.switchTo().activeElement().getInnerHtml());
};



回答3:


I managed to find a way to compare an element with the focused one without relaying to any attributes:

element(by.css('div.my-class')).equals(browser.driver.switchTo().activeElement())
    .then(equals => expect(equals).toBe(true));


来源:https://stackoverflow.com/questions/22753496/how-do-i-assert-an-element-is-focused

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!