AngularJS- How to test that a funtion in controller is defined using jasmine

时间:2016-04-07 10:35:42

标签: angularjs unit-testing jasmine angular-mock

I have following controller. During unit testing I want to first test that all the controller properties and functions are defined before unit testing the individual logic.

angular.module('sampleModule')
   .controller('SampleController', SampleController);

   SampleController.$inject =['sampleService'];

   function SampleController(sampleService){
      this.property1 = 'some data';
      this.property2 = 'some other data';

      this.getData = function(){
         //do something
      }
      this.postAttributes = function() {    
         sampleService.updateMethod(number,attributes)
             .then(function(response){
               //do something on successful update
             },function(response){
               //do something on unsuccessful update
          });
       }; 
    }

Here is the sample spec that I'm using. I'm able to verify that the controller properties are defined after creating the SampleController instance using $controller service. However when I perform the same assertion on functions, I get error saying function is undefined

describe('SampleController Test', function(){
    var $controller;
    var service;

    beforeEach(angular.mock.module('sampleModule')); 

    beforeEach(angular.mock.inject(function(_$controller_){
        $controller = _$controller_;
    }));

    it('Testing $scope variable', function(){
        var sampleController = $controller('SampleController', { 
            sampleService: service, //mocked factory service 
        });

        expect(sampleController.property1).toBeDefined();
        expect(sampleController.property2).toBeDefined();
        expect(sampleController.getData).toBeDefined(); //this assetion fails
    });

});

Third assetion fails with below error: Expected undefined to be defined.

What am I missing?! And is it a right approach to test all the controller properties and functions are defined before testing any individual logic?

1 个答案:

答案 0 :(得分:0)

请进行此更改。

describe("\n\nuser registration form testing", function () {


    describe("SampleController Test", function () {

        var scope;

        beforeEach(angular.mock.module('sampleModule')); 
        beforeEach(inject(function ($rootScope,_$controller_) {
            $controller = _$controller_;
            scope = $rootScope.$new();
        }))

        it('Testing $scope variable', function(){

            var sampleController = $controller('SampleController',{$scope: scope});
            expect(sampleController.property1).toBeDefined();
            expect(sampleController.property2).toBeDefined();
            expect(sampleController.getData).toBeDefined(); //this assetion fails
        });

    });


});