![](/img/trans.png)
[英]AngularJS - In Jasmine directive unit test, how can I trigger element.on("$destroy") event?
[英]How can I unit test a controller in an AngularJS Directive?
我的指令是:
window.map.directive('dosingFrequencies', [
function() {
return {
restrict: 'E',
scope: true,
templateUrl: '/views/directives/dosingFrequencies.html',
controller: function($scope, util) {
console.log('here we go!');
angular.extend($scope, {
model: createModel(),
addFrequency: function(med) {
med.frequencies.push(createFreqModel());
},
removeFrequency: function(med, index) {
med.frequencies.splice(index, 1);
},
showTimeChecked: function(freq) {
if (freq.showTime) {
freq.prn = false;
freq.quantity = '';
freq.quantityWhole = '';
freq.quantityFrac = '';
resetTimeToFirstLast(freq, this.model.facilityTimezone)
}
if (!freq.showTime) {
for (var z = 0; z < freq.doses.length; z++) {
freq.doses[z].quantity = '';
freq.doses[z].quantityWhole = '';
freq.doses[z].quantityFrac = '';
}
resetTimeToAllday(freq, this.model.facilityTimezone);
}
},
updateDosingForm: function(med) {
med.template.dosingForm = doseUnitChoices[med.med.dosingUnit] || ['', ''];
}
});
}
};
}
]);
我的测试是:
fdescribe('MedPickerController', function() {
var $scope;
beforeEach(function() {
module('mapApp');
var html = '<dosing-frequencies></dosing-frequencies>';
inject(function($compile, $injector) {
var $controller, $rootScope, $httpBackend;
$rootScope = $injector.get('$rootScope');
$httpBackend = $injector.get('$httpBackend');
$httpBackend.whenGET('/views/directives/dosingFrequencies.html').respond(200);
$scope = $rootScope.$new();
var elem = angular.element(html);
var compiled = $compile(elem)($scope);
var controller = elem.controller();
$scope.$digest();
});
});
it('should extend the scope', function() {
expect($scope.model).not.toBeUndefined();
});
});
但是,我的测试失败。 我的控制器中的console.log
也不会执行。 我做错了什么?
自己制作控制器。 不要将其设为匿名函数。
所以代替
{
// ... some directive options
controller: function() {
// Your controller's logic
}
}
做这样的事情。
{
// ... some directive options
controller: "MedPickerController"
}
然后像定义其他控制器一样分别定义您的控制器。 您甚至可以将它们放在同一文件中,没关系。
然后,此时您只是在编写控制器测试。 您不必担心这是一个指令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.