Search code examples
angularjstestingkarma-mocha

Angular Unit Testing: How do i call a named function


I have a controller, which contains a named function.

function controller($scope, ...){
   function foo(data){ 
     //logic for other stuff
     $log(data);
 }

 //some promise stuff
waiting.then(function(data){
  foo(data);
});

For the way that functions are available, i didnt want to assign foo to a scope variable, since doing something like this:

$scope.foo = function(data) {}

was frowned upon? (not sure...but since i am not calling foo from view, i dont see why i would)

My issue is, how do i call the foo function from a unit test "it" block?

i.e

  it('expect calling function', function(){
    foo(data);
});

This gives me error


Solution

  • Call foo function outside controller is impossible, because foo is closure - inner function defined and available only within controller function body. See https://developer.mozilla.org/cs/docs/Web/JavaScript/Closures#Lexical_scoping

    I prefer controllerAs syntax for angular controller. Controller is ordinary object constructor with properties and method defined on this. Binding to scope arises only during evaluation ng-controller directive (or route display).

    Generally then you can create controller instance in test, mock dependencies (waiting) and use spies for assert function call more easily.

    http://toddmotto.com/digging-into-angulars-controller-as-syntax/