prem89 prem89 - 8 months ago 46
AngularJS Question

Test a directive function through watch

I have a function in angular directive that gets triggered on watch. How do i test the timeout based scrolling activity of the function

since its not in scope?

scope.$watch('elementId', function(value) {
//How do i test scroll function contents?
scroll(element, value);

function scroll (pE, element) {
$timeout(function afterTimeout () {
var scrollTo = $('#' + element);
var container = $(pE);
container.animate({scrollTop : scrollTo[0].offsetTop - container[0].offsetTop - 10}, 'slow');
}, 250);

The detailed code is here


I have a few suggestions to clean up your code. The first thing to realize is that you should be injecting the mock $timeout object into your test and calling $timeout.flush(251) to make sure your code runs.

Like this:

it('test watch', inject(function($compile, $rootScope, $timeout) {
    // as before
    // test that your code has run

Another suggestion: instead of using jQuery's $ object, use $window.document or $document[0] to access the browser's native components. With this, you can write this:

var scrollTo = $document[0].getElementById(element);

and then you no longer have to access your scrollTo element with [0].