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對象數組。 –