我写了这个指令(工作正常)但是我在测试它时遇到了麻烦:
module.exports = /*@ngInject*/ function($filter) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$parsers.push(function(value) {
var phoneNumber;
if (scope.country === 'US' && value.length >= 10) {
phoneNumber = value.replace(/[ &()-.]+/g, '');
ngModel.$setViewValue(phoneNumber);
ngModel.$render();
} else {
phoneNumber = value;
}
return phoneNumber;
});
}
};
};
在阅读了200篇文章并失败后,我基本上处于第1区:
var factory = require('./us-phone.directive.js');
describe('US Phone Number directive', function() {
it('should remove dashes, parantheses, and spaces' , function() {
var value = '(555)555-5555';
var phoneNumber = '';
phoneNumber.should.equal('5555555555');
});
});
答案 0 :(得分:1)
有几件事要做:
triggerHandler('input')
触发它。 您需要手动启动摘要周期。
describe('myApp', function () {
var element;
beforeEach(function () {
module('myApp');
});
it('should replace special characters', function () {
element = angular.element('<input phone ng-model="value"/>');
inject(function ($rootScope, $compile) {
var scope = $rootScope.$new();
scope.value = '(555)-55 5555';
var compiled = $compile(element)(scope);
compiled.val(scope.value);
compiled.triggerHandler('input');
scope.$digest();
expect(scope.value).toBe('555555555');
});
});
});
我为你创造了一个小提琴:http://jsfiddle.net/trollr/q1vd1hqs/