HOWTO嘲笑的指令使用的服务 [英] Howto mock a service used in a directive

查看:167
本文介绍了HOWTO嘲笑的指令使用的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有以下指令:

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

目前它引发错误类型错误:无法读取的未定义的属性'AUTHUSER,因为我没有嘲笑 SessionService

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

推荐答案

SessionService.get 可以用茉莉花间谍被嘲笑,如果 SessionService 在加载的模块定义和 beforeEach :

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

或整体服务可以通过ngMock的方式来嘲笑:

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

这篇关于HOWTO嘲笑的指令使用的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆