[英]jasmine test is not working for angulardirective?
trying to test my directive with jasmine but is not failing where it should because of the wrong date(.demo): 尝试用茉莉花测试我的指令,但由于日期错误(.demo),未在应有的地方失败:
describe("Unit: Testing Directives - ", function() {
var $compile, $rootScope;
beforeEach(module('app'));
beforeEach(inject(function(_$compile_, _$rootScope_){
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
describe("Date Validation Directive - ", function(){
it('should show an date as valid', function(){
$rootScope.demo = '10/01/881';
var templateHTML = angular.element('<input class="blah" type="tel" ng-model="demo" my-date />');
var element = $compile(templateHTML)($rootScope);
$rootScope.$digest();
expect(element.hasClass('ng-valid')).toBe(true);
expect(element.hasClass('ng-invalid')).toBe(false);
});
});
});
this is what my directive looks like: 这是我的指令的样子:
var app = angular.module('app', []);
app.directive("myDate", function () {
return {
restrict: "A", //only activate on element attribute
require: "ngModel", //get hold of NgModelController
link: function (scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
var date_regexp = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
if (date_regexp.test(viewValue)) {
// it is valid
ctrl.$setValidity("myDate", true);
return viewValue;
} else {
// it is invalid, return undefined (no model update)
ctrl.$setValidity("myDate", false);
return undefined;
}
});
}
};
});
how can I get it working? 我该如何运作? plunkr: http://plnkr.co/edit/GYBvynRqdTTqXxnk7thN?p=preview plunkr: http ://plnkr.co/edit/GYBvynRqdTTqXxnk7thN?p=preview
This is because of the programmatic assignment of the model value. 这是由于模型值的编程分配。 $parsers
run when he value is modified through DOM. 通过DOM修改价值时, $parsers
运行。 When you change the model value programatically it is $formatters
that run. 以编程方式更改模型值时,将运行$formatters
。 So in your directive if you change $parsers
to $formatters
it will fail the test as you expected. 因此,在您的指令中,如果将$parsers
更改$parsers
$formatters
,它将无法按预期通过测试。
However you may need both of them in your directive and your real testing should be to test the logic inside the parsers/formatters, not how it is run (It has already been tested by angular) or how the classes are added by angular. 但是,您的指令中可能同时需要它们,而真正的测试应该是测试解析器/格式化程序中的逻辑,而不是测试它的运行方式(已通过angular测试过)或如何通过angular添加类。 If your validations are exposed through say a validator service, or even your directive's controller which provides the validation that would be a good target to test. 如果您的验证是通过验证程序服务,甚至是通过提供验证的指令的控制器公开的,那么验证将是一个很好的测试目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.