Question

I'm using angularJS and i understand how to test my $scope objects with karma-jasmine but i'm having difficulties testing regular functions and variables inside my controller file

//controller.js
angular.module('myApp').controller('mainCtrl', function ($scope) {
    $scope.name = "bob";

    var aNumber = 34;

    function myFunction(string){
      return string;
    }
});

what i would like to do is to test to see if expect(aNumber).toBe(34);

// test.js
describe('Controller: mainCtrl', function () {

  // load the controller's module
  beforeEach(module('myApp'));

  var mainCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    mainCtrl = $controller('mainCtrl', {
      $scope: scope
    });
  }));

  // understand this
  it('should expect scope.name to be bob', function(){
   expect(scope.name).toBe('bob');
  });

  // having difficulties testing this
  it('should expect aNumber to be 34', function(){
    expect(aNumber).toBe(34);
  });

  // having difficulties testing this    
  it('should to return a string', function(){
    var mystring = myFunction('this is a string');
    expect(mystring).toBe('this is a string');
  });


}); 
Était-ce utile?

La solution

It looks you are trying to test private variables declared in angular controller. The variables which are not exposed through the $scope cannot be tested, as they are hidden, and are visible only in a function scope inside the controller. More on private members and information hiding in javascript you can find here

The way how you should approach private fields in tests is by testing them through exposed api. If the variable is not used in any exposed publicly method it means that it's not used so it doesn't make sense to keep it and test it.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top