在指令链接函数

时间:2016-09-20 16:05:57

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

我正在尝试从指令的link函数测试$ resources服务调用。我的测试是查看是否使用正确的参数($ stateParams.id)调用服务。

服务:

AppServices.factory('lastReportService', ['$resource',function($resource){            
    return $resource('/endpoint/:id/report/',null, { id : '@id'})
}]);

指令:

AppDirectives.directive('directive', ['lastReportService','$stateParams', function(lastReportService,$stateParams) {
    return {
        restrict: 'E',
        templateUrl:'/static/views/directives/directive.html',
        scope:{
            object : '=',
        },
        link: function(scope, element, attrs) {
            lastReportService.get({id:$stateParams.id},
                function(response){ //DO STUFF WITH RESPONSE });            
            });
    }
}}]);

规格:

beforeEach(function() {
    inject(function ($compile, $rootScope, _$q_, lastReportService) {
        compile = $compile;
        scope = $rootScope.$new()
        object = {"id":"cd625c6e-944e-478e-b0f1-161c025d4e1a"};
        $stateParams = {"id":"cd625c6e-944e-478e-b0f1-161c025d4e1a"};
        $serviceForlastReportService = lastReportService;

        //Service Spy
        var lastReportGetDeferred = _$q_.defer();
        spyOn($serviceForlastReportService, 'get').and.callFake(function(){
            lastReportGetDeferred.promise.then(this.get.arguments[1]);
            return {$promise: lastReportGetDeferred.promise};
        });

        lastReportGetDeferred.resolve({report:'data'});
        adGroupTopNav = compile(angular.element('<directive object="object"></directive>'))(scope);

        scope.$digest();
       });
});
    it('should fetch last report service api to retrieve the last report information', function(){
        expect($serviceForlastReportService.get).toHaveBeenCalledWith({id:$stateParams.id});
    });

运行此测试时,我收到以下错误。 Expected spy get to have been called with [ Object({ id: 'cd625c6e-944e-478e-b0f1-161c025d4e1a' }) ] but actual calls were [ Object({ id: undefined }) ].

所以,这是我的问题,为什么不使用$ stateParams.id调用服务?

我是否错过了间谍配置?我应该以不同方式注入$ statePArams吗?

1 个答案:

答案 0 :(得分:0)

我认为你必须将你的模拟$stateParams对象注入你的工厂。没试过这个,但这可以在您的规范中使用

$provide.value('$stateParams',object);

当在服务中注入$stateParams

时,这应该使用模拟ID注入您的对象