【问题标题】:Testing $resource.get params inside a directive link function在指令链接函数中测试 $resource.get 参数
【发布时间】:2017-01-28 15:54:50
【问题描述】:

我正在尝试从指令的链接函数测试 $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 调用服务?

我是否遗漏了 Spy 配置上的某些内容?我应该以不同的方式注入 $statePArams 吗?

【问题讨论】:

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


    【解决方案1】:

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

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

    $stateParams 被注入到服务中时,这应该用模拟 id 注入你的对象

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 2016-05-28
      • 1970-01-01
      • 2015-05-25
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多