我目前正在使用 Jasmine 和 Karma(Testacular) 和 Web Storm 来编写单元测试。我无法监视初始化控制器时立即调用的方法。是否可以监视初始化控制器时调用的方法?
我的控制器代码,我试图监视的方法是getServicesNodeList()
.
myApp.controller('TreeViewController', function ($scope, $rootScope ,$document, DataServices) {
$scope.treeCollection = DataServices.getServicesNodeList();
$rootScope.viewportHeight = ($document.height() - 100) + 'px';
});
这是测试规范:
describe("DataServices Controllers - ", function () {
beforeEach(angular.mock.module('myApp'));
describe("DataServicesTreeview Controller - ", function () {
beforeEach(inject(function ($controller, $rootScope, $document, $httpBackend, DataServices) {
scope = $rootScope.$new(),
doc = $document,
rootScope = $rootScope;
dataServices = DataServices;
$httpBackend.when('GET', '/scripts/internal/servicedata/services.json').respond(...);
var controller = $controller('TreeViewController', {$scope: scope, $rootScope: rootScope, $document: doc, DataServices: dataServices });
$httpBackend.flush();
}));
afterEach(inject(function($httpBackend){
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
}));
it('should ensure DataServices.getServicesNodeList() was called', inject(function ($httpBackend, DataServices) {
spyOn(DataServices, "getServicesNodeList").andCallThrough();
$httpBackend.flush();
expect(DataServices.getServicesNodeList).toHaveBeenCalled();
}));
});
});
测试失败,说明该方法尚未被调用。我知道我应该模拟DataServices
并将其传递给测试控制器。但是,无论它是否是模拟方法,在监视该方法时,我似乎仍然会遇到同样的问题。任何人有任何想法或可以指出我处理此问题的正确方法的资源吗?