CAT CAT - 2 months ago 13
AngularJS Question

AngularJS unit test check if function without methods have been called

I'm using Jasmine to unit test my Angular app. It's pretty easy to test if a method of a function has been called using something like:

spyOn($rootScope, "$emit");
expect($rootScope.$emit).toHaveBeenCalled();


But I can't find a way to check when a function has been called (without a method), for e.g. I'm using
$anchorScroll()
; in one controller and I have no idea where to apply the above code to this guy. I've seen some Jasmine examples where they were using
expect(window.myFunction()).toHaveBeenCalled()
, but this doesn't work with Angular's DI.

JJJ JJJ
Answer

I can't try it myself at the minute but maybe you could just inject a mock $anchorScroll instead?

var $anchorScroll = jasmine.createSpy('anchorScroll');

$controller('MyCtrl', {
    $anchorScroll: $anchorScroll
});

expect($anchorScroll).toHaveBeenCalled();

This should just create a blank spy, one which will take any arguments and do nothing but keep track of the calls for test usage.

Comments