我已经开始使用karma并尝试测试我的代码。虽然我已经完成了常用功能并且能够测试功能和过滤器,但使用指令可以正常工作,但我对如何测试它感到茫然。
angular.module('myUtils').filter('Cents', function($filter) {
var CentsFilter = $filter('cents');
return function(Input) {
var Amount = 0;
if ( (Number(Input) === Input) && (Input % 1) === 0) { // Integer
Amount = Input / 100;
} else if ( (Number(Input) === Input) && ( (Input % 1) !== 0) ) { // Float
Amount = Input;
} else {
if ( isNaN(Input) ) {
Amount = parseInt(Input);
} else {
Amount = Input;
}
}
return CentsFilter(Amount);
};
});
angular.module('myUtils').directive('myCents',
function($filter) {
return {
restrict: 'A',
require: '^ngModel',
link: function($scope, element, attrs, ngModelControl) {
var myCentsFilter = $filter('Cents');
ngModelControl.$formatters.push(function(value) {
return myCentsFilter(value);
});
ngModelControl.$parsers.push(function(value) {
if ( value[0] == '$' ) {
value = value.substr(1);
}
if ( value.indexOf('.') !== -1 ) { // Contains a decimal, convert to cents
return Math.round(value * 100);
} else { // No decimal, assume cents already
return parseInt(value);
}
});
}
};
}
);
我有通过过滤器的测试,但不知道如何测试它的指令部分。
describe('myCents Filter', function() {
var Filter;
beforeEach(module('SLS_Utilities'));
describe('Currency Filter - Return values are Dollar Amounts', function() {
var Filter;
beforeEach(inject(function(_$filter_){
Filter = _$filter_;
}));
it('myCents filter exists', function() {
assert.isNotNull(Filter('myCents'));
});
it('should return the value $1.23 when passed 123', function() {
assert.deepEqual('$1.23', Filter('myCents')(123));
});
it('should return the value 123 when passed "123 ABC"', function() {
assert.deepEqual('$123.00', Filter('myCents')('123 ABC'));
});
it('should return the value 123 when passed "123"', function() {
assert.deepEqual('$123.00', Filter('myCents')("123"));
});
it('should return "" when not a number', function () {
assert.deepEqual('', Filter('myCents')('ABC'));
});
it('should return $123.45 when passed 123.45', function() {
assert.deepEqual('$123.45', Filter('myCents')(123.45));
});
});
});
这些测试将通过。我需要知道如何测试指令以查看我期望的正确结果,即从货币转换为美分并返回。
我见过简单的例子,但这是一个我无法理解如何测试的真实例子,因为它不是教程显示的简单字段替换。