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);
});
}
}
})();
的。当([])范围内,我进入IDS后,我要找回? – foxtrot3009
您输入服务应该返回的内容,以及允许测试您的指令的内容。如果服务应该返回一个ID数组的承诺,那么输入一个ID数组。如果它应该返回Post对象数组的承诺,则输入Post对象数组。 –