如何模拟指令中使用的服务



我们有以下指令:

(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;
        }
    }
})();

在测试过程中如何模拟SessionService

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");
    });
});

目前它抛出错误TypeError: Cannot read property 'authUser' of undefined,因为我没有模拟SessionService

SessionService.get可以用Jasmine spy模拟,如果SessionService在加载的模块中定义并注入beforeEach:

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

或者整个服务可以通过ngMock:进行模拟

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

当有很多东西需要模拟时,可以使用一个具有模拟依赖关系的模块:

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

最新更新