I have started working with karma and trying to test my code. While I have made common functions and have been able to test the functions and filters, using the directives works, but I am at a loss on how to test it.
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);
}
});
}
};
}
);
I have tests that pass the filter, but do not know how to test the directive part of this.
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));
});
});
});
These tests will pass. I need to know how to test the directive to see the proper results that I am expecting, which is converting from money to cents and back.
I have seen simple examples, but this is a real example that I cannot see to understand how to test, as it is not a simple field replacement that the tutorials are showing.
Aucun commentaire:
Enregistrer un commentaire