Vladimir Mironov
Vladimir Mironov

Reputation: 685

mocking angular $element in jasmine

I need to test a directive controller with $element inside. So I've got a function like this one:

function func($event) {
        $element.find('#la-la-la').focus();
}

and render it in the test:

template = $compile(element)($scope);
$scope.$apply();

controller = element.controller('myDirective');

And what I'm trying to do is to test this function inside that controller for the directive.

describe('func method', function testFunc() {
    it('should focus on element', function checkFocusing() {
        controller.func();
        expect(focusSpy).toHaveBeenCalled();
    });
});

Where "focusSpy" is a spy inside mocked $element service. But it seems like if I use $provide.service('$element', ...) it is not found by the test. Injecting it to $scope.$element before compiling doesn't work either. Thank you!

Upvotes: 4

Views: 2280

Answers (1)

Vladimir Mironov
Vladimir Mironov

Reputation: 685

Alright, I've found a possible solution. You can't mock $element because it is a private variable of directives controller, but since it's a jQuery element you can spy on jQuery itself like that:

describe('func method', function testFunc() {
    it('should focus on element', function checkFocusing() {
        spyOn($.fn, 'find').and.callThrough();
        spyOn($.fn, 'focus').and.callThrough();

        controller.func();

        expect($.fn.find).toHaveBeenCalledWith('#la-la-la');
        expect($.fn.focus).toHaveBeenCalled();
    });
});

Upvotes: 2

Related Questions