According to the How do I assert an element is focused? thread, you can check if an element is focused by switching to an activeElement()
and assert this is the
It's weird that it's expecting a promise only and could not handle a webdriver element... I had the same HUGE stacktrace as you.
Anyway, would you accept this kind of solution: send a "dumb" promise with a nice comment to justify why you had to do that. It's more a workaround than a semantic solution I admit.
expect(page.element.getInnerHtml())
.toEqual(browser.driver.switchTo().activeElement().getInnerHtml());
It's working for me ;)
EDIT: Bonus answer
The reason you can't call expect with a WebElement comes from the Webdriver Control Flow Principle (I'm sure you already know about) and this line in jasminewd, the adapter for jasmine to Webdriver developped and used by Protractor ;)
For the future readers, I've created a custom matcher to assert if an element is active/focused:
beforeEach(function() {
jasmine.addMatchers({
toBeActive: function() {
return {
compare: function(elm) {
return {
pass: elm.getId().then(function (activeElementID) {
return browser.driver.switchTo().activeElement().getId().then(function (currentElementID) {
return jasmine.matchersUtil.equals(currentElementID, activeElementID);
});
})
};
}
};
}
});
});
Usage:
expect(element(by.css("#myid")).toBeActive();
You need to come up with a way to tell Protractor/webdriver how to find your element on the page. Protractor uses JavaScript to find elements, so any of the tools available for inspecting the DOM are available. Protractor and webdriver wrap these APIs in the various by
flavors:
http://angular.github.io/protractor/#/api?view=ProtractorBy
In addition to the basic flavors, Protractor adds Angular-aware flavors (so you can search by Angular binding, etc).
If your element does not have any distinguishing characteristics, then it might be worth adding something to make it easier to test. Or, (though this is often frowned upon because its so fragile), you can use an xpath. See https://github.com/angular/protractor/blob/master/docs/locators.md
You can simply check the text (or anything else) of the element:
var currentElement = browser.switchTo().activeElement();
expect(currentElement.getText()).toEqual(page.element.getText());
What about using CSS selectors and :focus
expect(element.all(by.css('#myid:focus')).count()).toBe(1);
I solved it by using protractor's: ElementFinder.prototype.equals
const activeElement = await browser.driver.switchTo().activeElement();
const potentialyFocusedElement = await component.$('your-locator');
const isFocused = await potentialyFocusedElement.equals(activeElement);
I am not sure how exactly equals
work, if it does a deep compare, or it somehow compares instances. But it works.
Note that you can not call activeElement.equals(...)
since it is not an ElementFinder, it is a WebElement
.