Angular and karma (jasmine) : How can I find an element by class

29,042

Solution 1

find by class name is not supported by the AngularJS find function. Instead you can use vanilla javascript for this:

var result = element[0].querySelectorAll('.findme');

Now you can check if the result variable has a class of findme by wrapping it in an angular element.

angular.element(result).hasClass('findme')

Fiddle

Solution 2

this should do the trick: expect(element[0].querySelectorAll("div.trigger").length).not.toBe(0);

Share:
29,042

Related videos on Youtube

Hudvoy
Author by

Hudvoy

Updated on December 09, 2020

Comments

  • Hudvoy
    Hudvoy over 3 years
    beforeEach(function () {
    
        html = '<div class="dropdown">'+
                  '<div class="trigger" >trigger</div>'+
                  '<div class="dropdown">body</div>'+
               '<div>';
    
        inject(function ($compile, $rootScope) {
    
            scope    = $rootScope.$new();
            element  = angular.element(html);
            compiled = $compile(element);
    
            compiled(scope);
            scope.$digest();
    
            // HERE NOT WORKING
            var trigger == element.find('div.trigger');
            var dropdown == element.find('.dropdown');
    
            // trigger and dropdown have both length 0
    
        });
    
        // Test doesn't pass
        it('should find the right element'), function () {
            expect(trigger.hasClass('trigger')).toBe(true);
        }
    
    });
    

    I am trying to unit test a directive, but I can't find element by class.

    I would like to be able to find element with something like:

    var trigger == element.find('div.trigger') // doesn't find anything.
    

    but now I am only able to do it like this:

    var triggers = element.find('div') // return an array of length 2.
    var trigger = triggers[0];
    

    How can I find an element by class?

  • Petr Peller
    Petr Peller almost 9 years
    Why do you need to use hasClass on something returned by querySelectorAll('.findme')? It should always contain the findme class, shouldn't it?
  • Nicolas Del Valle
    Nicolas Del Valle over 8 years
    Like @PetrPeller said, I don't think thats necessary. Maybe using something like expect(result).toBeDefined(); would make more sense.
  • Nicolas Del Valle
    Nicolas Del Valle over 8 years
    Or using expect(result).not.toBe(null);