我搜索了很长时间但没找到解决办法。我是业力/茉莉花测试的新手,但到目前为止它已经扼杀了我的生产力。我尝试以TDD方式编写测试但是我无法让测试工作,即使代码完成了我想要的工作。
我有这个指令来验证输入并在模糊时显示错误:
angular.module('myApp')
.directive('formValidate', function() {
var message = {
error: '',
warning: '',
notification: ''
};
return {
link: function(scope, element, attrs) {
scope.message = message;
var formElements = element.find('input');
for (var i = 0; i < formElements.length; i++) {
switch (formElements[i].getAttribute('type')) {
case 'email':
validateEmail(scope, formElements[i]);
break;
case 'password':
validatePassword(scope, formElements[i]);
default:
break;
}
}
}
};
function promptUser(scope, text) {
scope.$apply(function() {
scope.message.error = text;
});
}
function validateEmail(scope, element) {
var element = angular.element(element);
element.bind('blur', function() {
if (element.hasClass('ng-invalid-email')) {
promptUser(scope, 'Invalid email format');
} else {
promptUser(scope, '');
}
});
}
function validatePassword (scope, element) {
var element = angular.element(element);
element.bind('blur', function() {
if (element.hasClass('ng-invalid-minlength')) {
promptUser(scope, 'Password must be at least 6 characters');
} else {
promptUser(scope, '');
}
});
}
});
我试图用以下方法测试它:
'use strict';
describe('formValidation directive', function() {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 50;
beforeEach(module('myApp'));
beforeEach(module('ui.router'));
var $compile, $scope;
beforeEach(module('myApp'));
beforeEach(module('ui.router'));
beforeEach(inject(function(_$rootScope_, _$compile_) {
$compile = _$compile_;
$scope = _$rootScope_.$new();
}));
describe('register', function() {
var $element, $controller, testForm, form;
beforeEach(function() {
testForm = angular.element('<form name="form" form-validate>' + '<p class="form-error">{{ message.error }}</p>' + '<input type="email" ng-model="register.email" name="email" placeholder="email">' + '<input type="password" ng-model="register.password" name="register-password" placeholder="password" ng-minlength="6">' + '<input type="password" ng-model="register.passwordVerify" name="password-verify" placeholder="password verify" ng-minlength="6">' + '<input type="submit" id="login-btn" value="Submit" >' + '</form>');
$element = $compile(testForm)($scope);
$scope.$digest();
});
describe('individual field', function() {
it('adds correct content to error message', function() {
//How can I set the value of an input here
//And then trigger a blur event to run the directive
var input = testForm.find('input')[0];
var angInput = angular.element(input);
angInput.val('test'); // I console.log'd this and it doesn't seem to do anything
expect($scope.message.error === 'Invalid email format').toEqual(true);
});
it('does not add error if format is valid', function() {
});
it('unhides error element when valid', function() {
});
});
describe('all fields', function() {
});
});
我真的很想开始使用角度TDD,但这花了太长时间。
答案 0 :(得分:0)
你要追求的重要一点是:
Completable
(来自Setting view value an input field in a unit test of an angular form directive)