我目前正在使用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
并将其传递给测试控制器。但似乎我在监视该方法时仍会遇到同样的问题,无论是否是模拟。任何人都有任何想法,或者可以指出我正确处理这个问题的资源吗?
答案 0 :(得分:5)
编写单元测试时,应该隔离每段代码。在这种情况下,您需要隔离您的服务并单独测试它。创建服务的模拟并将其传递给您的控制器。
var mockDataServices = {
getServicesNodeList: function () {
return <insert your sample data here > ;
}
};
beforeEach(inject(function ($controller, $rootScope, $document) {
scope = $rootScope.$new(),
doc = $document,
rootScope = $rootScope;
var controller = $controller('TreeViewController', {
$scope: scope,
$rootScope: rootScope,
$document: doc,
DataServices: mockDataServices
});
}));
如果是您的服务正在发出$ http请求,您可以从单元控制器测试中删除该部分。编写另一个单元测试,测试服务在初始化时正在进行正确的http调用。