I have an angular.js application that should set the focus to a specific element when doing something (ie, set the focus to an invalid form field to let the user correct the error).
I'm trying to test this behavior within an angular-e2e test:
it('should set the focus to the invalid field', function() {
input('email').enter('foo'); // this is not a valid email address
element(/* submit button */).click(); // try to submit the form
// How do I do this?
expect(element(/* email input element */)).toHaveTheFocus();
});
How can I expect a certain element to (not) have the focus? I already tried the ':focus' selector
expect(element('input[id="..."]:focus').count()).toBe(1);
but no success (inspired by Testing whether certain elements are visible or not).
To set the focus, I use the idea of How to set focus on input field?
I was also writing unit tests for this and ended up using a spy on the DOM focus() function (which is, as far as I know, not possible/desireable for e2e tests).
I see two options here. The first, which I really recommend, specially on E2E tests, is to use Jasmine-jQuery which provides the toBeFocused
matcher which deals with this.
If you don't want to include Jasmine-jQuery because it's too big or because you don't like it, then you have two options:
document.activeElement
DOMELEMENT.ownerDocument.activeElement
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With