Angularjs 角度单元测试:隔离模块上定义的某些组件
我继承了一个使用Karma和Jasmine的大型AngularJS项目,我试图遵循之前制定的惯例,但在单元测试指令/控制器模块时遇到了麻烦。每个模块的定义如下:Angularjs 角度单元测试:隔离模块上定义的某些组件,angularjs,unit-testing,angularjs-directive,jasmine,angularjs-controller,Angularjs,Unit Testing,Angularjs Directive,Jasmine,Angularjs Controller,我继承了一个使用Karma和Jasmine的大型AngularJS项目,我试图遵循之前制定的惯例,但在单元测试指令/控制器模块时遇到了麻烦。每个模块的定义如下: angular .module('ap.panels.ContinuousDeliverySearchPanel', []) .directive('continuousDeliverySearchPanel', ContinuousDeliverySearchPanel) .controller('continuousDe
angular
.module('ap.panels.ContinuousDeliverySearchPanel', [])
.directive('continuousDeliverySearchPanel', ContinuousDeliverySearchPanel)
.controller('continuousDeliverySearchPanelCtrl', ContinuousDeliverySearchPanelCtrl);
function ContinuousDeliverySearchPanel() {
return {
restrict: 'E',
templateUrl: '/panels/continuous-delivery-search-panel/continuous-delivery-search-panel.html',
controller: 'continuousDeliverySearchPanelCtrl',
controllerAs: 'vm',
bindToController: true,
scope: {
search: '='
}
};
}
module('foobar', function($provide, $controllerProvider) {
$controllerProvider.register('FooBarController', function($scope) {
// Controller Mock
});
});
其中,模块上同时定义了指令和控制器,并且控制器绑定到该指令。我想创建两组测试,一组用于控制器,另一组用于指令。我遇到的问题是,在测试指令时,我只想测试元素是否已正确编译,但我不得不处理控制器的http调用和依赖项。以下是我的指令测试示例:
describe('ap.panels.ContinuousDeliverySearchPanel', function () {
var scope, template, element;
beforeEach(module('ap.panels.ContinuousDeliverySearchPanel'));
beforeEach(inject( function ($rootScope, $compile){
scope = $rootScope.$new();
template = angular.element('<continuous-delivery-search-panel></continuous-delivery-search-panel>');
element = $compile(template, scope);
scope.$digest();
}));
it('Should: compile search panel directive', function() {
expect(element).toBeDefined();
});
});
description('ap.panels.ContinuousDeliverySearchPanel',函数(){
var范围、模板、元素;
每个模块之前(模块('ap.panels.ContinuousDeliverySearchPanel');
beforeach(注入(函数($rootScope,$compile){
scope=$rootScope.$new();
模板=角度元素(“”);
元素=$compile(模板,范围);
范围。$digest();
}));
它('应该:编译搜索面板指令',函数(){
expect(element.toBeDefined();
});
});
调用$compile时,continuousDeliverySearchPanelCtrl会运行并开始抛出错误,因为它有一堆依赖项和http请求,这些依赖项和请求没有被模拟或处理。然而,我不想嘲笑这些,因为我甚至没有测试控制器。我想在另一个文件中单独执行此操作,在该文件中隔离控制器以进行测试
有没有办法传入一个空的控制器或仅隔离指令,以便成功测试它是否编译?是的,您只需模拟控制器即可 试着这样做:
angular
.module('ap.panels.ContinuousDeliverySearchPanel', [])
.directive('continuousDeliverySearchPanel', ContinuousDeliverySearchPanel)
.controller('continuousDeliverySearchPanelCtrl', ContinuousDeliverySearchPanelCtrl);
function ContinuousDeliverySearchPanel() {
return {
restrict: 'E',
templateUrl: '/panels/continuous-delivery-search-panel/continuous-delivery-search-panel.html',
controller: 'continuousDeliverySearchPanelCtrl',
controllerAs: 'vm',
bindToController: true,
scope: {
search: '='
}
};
}
module('foobar', function($provide, $controllerProvider) {
$controllerProvider.register('FooBarController', function($scope) {
// Controller Mock
});
});