vendredi 4 décembre 2015

Howto mock a service used in a directive

We have the following directive :

(function() {
    'use strict';
    ff.directive('mySwitchUserDirective', mySwitchUserDirective);

    mySwitchUserDirective.$inject = ['SessionService'];

    function mySwitchUserDirective(SessionService) {
        var directive = {
            restrict: 'E',
            template: '<img ng-src="{{userImage}}" width="35px" style="border-radius: 50%; max-height: 35px;" />',
            link: linkFunc
        };

        return directive;

        function linkFunc(scope, element, attrs, ctrl) {
            scope.userImage = SessionService.get().authUser.picture;
        }
    }
})();

How do I mock the SessionService during my test?

describe('mySwitchUser', function() {
    var $compile,
    $rootScope;

    beforeEach(module('myApp'));

    beforeEach(inject(function(_$compile_, _$rootScope_){
        $compile = _$compile_;
        $rootScope = _$rootScope_;
    }));

    it('Replaces my-switch-user element with the appropriate content', function() {
        var element = $compile("<my-switch-user></my-switch-user>")($rootScope);
        $rootScope.$digest();
        expect(element.html()).toContain("ng-src");
    });
});

Currently it throws the error TypeError: Cannot read property 'authUser' of undefined, because I didn't mock the SessionService.

Aucun commentaire:

Enregistrer un commentaire