prem89 prem89 - 1 year ago 106
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

Answer Source

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].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download