Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 957
Hudvoy Avatar asked May 28 '14 21:05

Hudvoy


People also ask

What is fixture detectChanges ()?

fixture is a wrapper for our component's environment so we can control things like change detection. To trigger change detection we call the function fixture.detectChanges() , now we can update our test spec to: Copy it('login button hidden when the user is authenticated', () => { expect(el. nativeElement. textContent.

What is fixture in jasmine?

Jasmine Fixtures is an add-on for the behavior-driven development framework, Jasmine. If you're using Jasmine to test the JavaScript in your Ruby projects and you want to test your DOM and bindings, you can use Jasmine Fixtures.


1 Answers

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

like image 54
Dieterg Avatar answered Sep 29 '22 06:09

Dieterg