【发布时间】:2015-07-12 21:29:13
【问题描述】:
我在这里有一个指令,我正在尝试编写一个单元测试 - 第一次做这种类型的事情。我不知道该怎么做。这是指令代码和 HTML:
app.directive('passwordMatch', [function () {
return {
restrict: 'A',
scope:true,
require: 'ngModel',
link: function (scope, elem, attrs, control) {
var checker = function () {
var e1 = scope.$eval(attrs.ngModel);
var e2 = scope.$eval(attrs.passwordMatch);
if(e2!=null)
return e1 == e2;
};
scope.$watch(checker, function (n) {
control.$setValidity("passwordNoMatch", n);
});
}
};
}]);
<form name="signupForm">
<div class="form-group">
<div class="col-sm-7">
<span class="block input-icon input-icon-right">
<input type="password" class="register" name="password" placeholder="Password" ng-model="signup.password" required/>
</span>
</div>
</div>
<div class="form-group">
<div class="col-sm-7">
<span class="block input-icon input-icon-right">
<input type="password" class="register" name="password2" placeholder="Confirm Password" ng-model="signup.password2" password-match="signup.password" required/>
<small class="errorMessage" data-ng-show="signupForm.password2.$dirty && signupForm.password2.$error.passwordNoMatch && !signupForm.password2.$error.required"> Password do not match.</small>
</span>
</div>
</div>
</form>
这就是我正在尝试的测试。因此,读取 TypeError: 'undefined' is not an object (evalating 'scope.signup.password = '123'') 给我一个错误
describe('passwordMatch Directive - ', function() {
var scope, $compile, $window, element;
beforeEach(function() {
module('myApp');
inject(function(_$compile_, _$rootScope_, _$window_) {
$compile = _$compile_;
scope = _$rootScope_.$new();
$window = _$window_;
})
})
it('should indicate invalid when the passwords do not match.', function() {
scope.signup.password = '123';
scope.signup.password2 = '1234';
element = $compile(angular.element('<input type="password" class="register" name="password" placeholder="Password" ng-model="signup.password" required/> <input type="password" class="register" name="password2" placeholder="Confirm Password" ng-model="signup.password2" password-match="signup.password" required/>'))(scope);
scope.$apply();
console.debug('element html - ' + element.html());
expect(element.html().indexOf('ng-invalid')).toBeGreaterThan(0);
});
it('should indicate valid when the passwords do not match.', function() {
scope.signup.password = '123';
scope.signup.password2 = '123';
element = $compile(angular.element('<input type="password" class="register" name="password" placeholder="Password" ng-model="signup.password" required/> <input type="password" class="register" name="password2" placeholder="Confirm Password" ng-model="signup.password2" password-match="signup.password" required/>'))(scope);
scope.$apply();
console.debug('element html - ' + element.html());
expect(element.html().indexOf('ng-valid')).toBeGreaterThan(0);
});
});
非常感谢您的帮助
编辑:我刚刚注意到在注释掉 scope.signup.password = '123' 等时,调试语句没有返回任何内容 - 只是 DEBUG: 'element html - ',所以 element.html() 没有做任何事情?
【问题讨论】:
标签: javascript angularjs unit-testing