指令单元测试中的存根angular服务



我有这样一个指令:

app.directive('myDirective', ['my', function(myService){
return {
    restrict: 'E',
    scope: {
        resourcePath: '='
    },
    priority: 999,
    transclude: true,
    template: '<ng-transclude ng-if="func()"></ng-transclude>',
    link: function($scope){
        $scope.func = function(){
            return permissionsService.checkSomething(true);
        };
    }
};}]);

,这是服务:

angular.module('services.my', []).service('my', ['$http', function myService($http) {
//public:
this.checkSomething = function (param) {
    return param;
};}]);

我如何存根myService并注入到指令依赖?

对于控制器,这很容易,因为您可以自己创建控制器。

对于指令依赖,你必须使用$provide来覆盖默认实现并提供一个虚拟依赖

beforeEach(module(function ($provide) {
    $provide.service('my', function () { 
        this.checkSomething= function() { };
    });
}));

最新更新