lundi 26 janvier 2015

Spyon element.width() in angular directive test

I am trying to test a directive in angular that uses JQuery.


Here's the link function content:



var parent = element.parent();

function getElementWidth() {
return element.width();
}

function updateWidth() {
var w = element.width();
var p = parent.width();
var diffParent = element.width() - parent.width();
if (diffParent > 0) {
parent.addClass('show-more')
}
else {
parent.removeClass('show-more')
}
}
scope.$watch(getElementWidth, updateWidth, true);


What I want to test is that the class is correctly added/removed depending on diffParent.


Here's what I've tried so far:



describe('test directive', function() {
var element, parent, scope;
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();

element = '<parent><div mydirective></parent>';
element = $compile(element)(scope);
angular.element(document).find('body').append(element);

parent = element;
element = element.find('[mydirective]');
scope.$digest();
}));

it('should add class to the parent when needed', function() {
spyOn(element, 'width').and.returnValue(100);
spyOn(parent, 'width').and.returnValue(50);
scope.$digest();
expect(element.parent().hasClass('show-more')).toBeTruthy();
});


});


Aucun commentaire:

Enregistrer un commentaire