Using element.find() by class in Angular Unit testing
Asked Answered
E

1

13

When running this test, I keep getting the error Expected undefined to be true.

it('should have the right classes', function() {
   // this doesnt work
   expect(element.find('.exampleClass').hasClass('ng-hide')).toBe(true);

   // but this works
   expect(element.find('span').hasClass('ng-hide')).toBe(true);
});

How can I use jqlite to find an element by id and class?

Emulsifier answered 7/7, 2015 at 2:17 Comment(1)
You can't. jqLite doesn't support selectorsNeoprene
S
13

That is because angular-jqlite (very lightweight library when compared to jquery itself) find is limited to look up by tag names only. You can use element.querySelector(All) and wrap it in angular.element. i.e

  var elm = element[0];
  expect(angular.element(elm.querySelector('.exampleClass')).hasClass('ng-hide')).toBe(true);

  //Or even
  expect(elm.querySelector('.exampleClass.ng-hide')).toBeDefined();

See documentation

find() - Limited to lookups by tag name

Stanhope answered 7/7, 2015 at 2:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.