2016-04-17 79 views
0

我试图对调用服务来检索帖子的指令进行单元测试,并且对如何测试指令感到困惑。通常只需编译指令元素即可轻松进行指令测试,但此指令元素通过get调用来调用帖子。我如何测试这个?角度指令与服务的单元测试

(function() { 
    'use strict'; 

    describe('Post directive', function() { 
    var element, scope, postService, $rootScope, $compile, $httpBackend; 

    beforeEach(module('madkoffeeFrontend')); 
    beforeEach(inject(function(_postService_, _$rootScope_, _$compile_, _$httpBackend_) { 
     postService = _postService_; 
     $httpBackend = _$httpBackend_; 
     $rootScope = _$rootScope_; 
     $compile = _$compile_; 
     // $httpBackend.whenGET('http://madkoffee.com/wp-json/wp/v2/posts?per_page=3').passThrough(); 
     scope = $rootScope.$new(); 
     spyOn(postService, 'getPosts'); 
     element = $compile('<posts post-num="3"></posts>')(scope); 
     scope.$digest(); 
    })); 

    it('should get the posts successfully', function() { 
     expect(postService.getPosts).toHaveBeenCalled(); 
    }); 

    // it('should expect post to be present', function() { 
    // expect(element.html()).not.toEqual(null); 
    // }); 

    }); 
})(); 

这是控制器:

(function() { 
    'use strict'; 

    angular 
    .module('madkoffeeFrontend') 
    .directive('posts', postsDirective); 

    /** @ngInject */ 
    function postsDirective() { 
    var directive = { 
     restrict: 'E', 
     scope: { 
     postNum: '=' 
     }, 
     templateUrl: 'app/components/posts/posts.html', 
     controller: PostController, 
     controllerAs: 'articles', 
     bindToController: true 
    }; 

    return directive; 

    /** @ngInject */ 
    function PostController($log, postService) { 
     var vm = this; 

     postService.getPosts(vm.postNum).then(function(data) { 
     $log.debug(data); 
     vm.posts = data; 
     }).catch(function (err) { 
     $log.debug(err); 
     }); 
    } 
    } 
})(); 

回答

0

不要叫getPosts()从测试:这是没有意义的。

告诉窥探的服务返回什么。它使用http获取帖子的事实与该指令无关。您正在对指令进行单元测试,而不是服务。所以你可以假设服务返回它应该返回的内容:对帖子的承诺。

告诉窥探postService什么返回:

spyOn(postService, 'getPosts').and.returnValue(
    $q.when(['some fake post', 'some other fake post'])); 
+0

的。当([])范围内,我进入IDS后,我要找回? – foxtrot3009

+0

您输入服务应该返回的内容,以及允许测试您的指令的内容。如果服务应该返回一个ID数组的承诺,那么输入一个ID数组。如果它应该返回Post对象数组的承诺,则输入Post对象数组。 –