Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular e2e tests: How can I check if an element got the focus?

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).

like image 522
Nils Wilhelm Avatar asked Nov 13 '22 01:11

Nils Wilhelm


1 Answers

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:

  • Compare the button with the document's active element, can access it with: document.activeElement
  • Compare the button with the document's active element by getting it from the element itself (this is the way jasmine-jquery does it) with: DOMELEMENT.ownerDocument.activeElement
like image 56
Antonio Laguna Avatar answered Nov 15 '22 10:11

Antonio Laguna