Search code examples
angularjsunit-testingjqlite

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


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?


Solution

  • 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