I have a tasty directive that adds form placeholder support to browsers that don't support placeholders such as IE9. The directive looks like this:
angular
.module('app')
.directive('placeholder', placeholder);
function placeholder(PlaceholderSupportService, $timeout) {
var directive = {
restrict: 'A',
link: link
};
return directive;
function link(scope, element, attrs) {
if (PlaceholderSupportService() || attrs.type === 'password') {
return;
}
$timeout(replaceVal, 0);
element.bind('focus', focus);
function focus() {
if (element.val() === attrs.placeholder) {
$timeout(emptyVal, 0);
}
}
element.bind('blur', blur);
function blur() {
if (element.val() === '') {
$timeout(replaceVal, 0);
}
}
function emptyVal() {
element.val('');
}
function replaceVal() {
element.val(attrs.placeholder);
}
}
}
I want to unit test this with Karma. The PlaceholderSupportService() function either returns true or false, which either triggers the directive functionality to execute or not (in the first if statement). For unit testing I want to be able to mock that true or false value to see if the correct HTML is rendered in each situation. How do I mock that response?
My test so far looks like this:
describe('placeholder directive', function() {
var $compile,
$rootScope;
beforeEach(angular.mock.module('app'));
beforeEach(inject(function(_$compile_, _$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('Renders the correct HTML', function() {
// ** SOME HOW SET PlaceholderSupportService() to false **
var element = $compile('<input name="test" placeholder="Test" />')($rootScope);
$rootScope.$digest();
expect(element[0].value).toBe('Test');
});
});
Aucun commentaire:
Enregistrer un commentaire