1
votes

I have a directive with the below link function. The setOver and setRating are functions in the directives' controller.

function (scope, iElem) {
            return angular.forEach(iElem.children(), function (ul) {
                return angular.forEach(ul.children, function (li) {
                    li.addEventListener('mouseover', function () {
                        return scope.setOver(parseInt($(li).attr('data-val')));
                    });
                    li.addEventListener('mouseout', function () {
                        return scope.setOver(0);
                    });
                    return li.addEventListener('click', function () {
                        return scope.setRating(parseInt($(li).attr('data-val')), ul);
                    });
                });
            });
        }

The template of the directive is as below.

<div><ul><li ng-class="{\'glyphicon-star active\':model>0,\'glyphicon-star-empty\':model<=0,\'over\':over>0}" data-val=1>this is a test</li><li ng-class="{\'glyphicon-star active\':model>1,\'glyphicon-star-empty\':model<=1,\'over\':over>1}" data-val=2>this is a test</li></ul></div>

I have the below and it is not working.

element = compile('....')(scope); // abridged to be concise

angular.forEach(element.children(), function (ul) {
                angular.forEach(ul.children, function (li) {
                    if (i === 0) {
                        var mouseOverEvent = jQuery.Event('mouseover');
                        $(li).trigger(mouseOverEvent);
                        console.log(li);
                        expect($(li).hasClass('over')).toBe(true);
                        i++;
                    }
                });
            });

I want to know how I can simulate the mouseover, mouseout and click events on the li element.

2

2 Answers

0
votes

Did you try

$(li).trigger('mouseover');

? Please let me know if this works. I'm investigating how to test mouseover/out events myself. =)

If that works, you can leave out out the var mouseOverEvent = jQuery.Event('mouseover'); line...

0
votes

I was wondering this today as well, and it seems to be working for me.

The code in your answer is a bit too stripped down to work with (maybe you can provide a JSFiddle or something similar) but in any case:

You might have to attach the element to the DOM before the trigger('mouseover') works.

angular.element(document).find('body').append(element);

You probably have to remove the element from the DOM after your tests as well because I don't think that will be cleaned up properly otherwise.

In Jasmine:

afterEach(function () {
  angular.element(document).find('#some-kind-of-identifier-for-your-element').remove();
});