我正在尝试对调用服务来检索帖子的指令进行单元测试,并对如何测试指令感到困惑。通常只需编译指令元素就可以轻松进行指令测试,但是这个指令元素通过get调用来调用posts。我该如何测试?
(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 :(得分:0)
不要从测试中调用getPosts():这没有意义。
告诉间谍服务返回什么。它使用http来获取帖子这一事实与该指令无关。您是对指令进行单元测试,而不是服务。所以你可以假设服务返回它应该返回的内容:帖子的承诺。
告诉spied postService要返回的内容:
spyOn(postService, 'getPosts').and.returnValue(
$q.when(['some fake post', 'some other fake post']));