Howto mock a service used in a directive

只愿长相守 提交于 2019-12-13 04:53:32

问题


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.


回答1:


SessionService.get can be mocked with Jasmine spy, if SessionService was defined in loaded modules and injected in beforeEach:

spyOn(SessionService, 'get').and.callFake(() => ({
  authUser: {
    picture: 'wow.jpg'
  }
}));

Or the whole service can be mocked by means of ngMock:

beforeEach(module('myApp', {
  SessionService: {
    get: () => ({
      authUser: {
        picture: 'wow.jpg'
      }
    })
  }
}));

When there are a lot of things that should be mocked, it is acceptable to have a module with mocked dependencies instead:

beforeEach(module('myApp', 'myApp.mocked'));


来源:https://stackoverflow.com/questions/34096198/howto-mock-a-service-used-in-a-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!