【问题标题】:Howto mock a service used in a directive如何模拟指令中使用的服务
【发布时间】:2015-12-04 19:41:39
【问题描述】:

我们有以下指令:

(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

【问题讨论】:

    标签: unit-testing angularjs-directive karma-jasmine


    【解决方案1】:

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

    当有很多东西需要mock时,可以使用一个带有mocked依赖的模块来代替:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-14
      • 2017-02-14
      相关资源
      最近更新 更多