AngularJs unit test - Check if “Init” function was called

爱⌒轻易说出口 提交于 2019-12-11 01:52:51

问题


I'm using jasmine as testframework and I've the following Controller I want to test. And I allways have a Init() function where I place my initialization calls for this Controller.

Now I want to test if the Init function was called when the controller was initialized.

function UnitTestsCtrl() {
   var that = this;
   this.Init();
}

UnitTestsCtrl.prototype.Init = function() {
    var that = this;
    //Some more Stuff
}

angular.module("unitTestsCtrl", [])
       .controller("unitTestsCtrl", UnitTestsCtrl);

But I was not able to check if the Init function was called on controller creation. I know my example doesn't work because the spy is set on the Init function after creation.

describe('Tests Controller: "UnitTestsCtrl"', function() {
var ctrl;

   beforeEach(function() {
         module('app.main');
         inject(function ($controller) {
            ctrl = $controller('unitTestsCtrl', {});
         });
   });

   it('Init was called on Controller initialize', function () {
       //thats not working
       spyOn(ctrl, 'Init');
       expect(ctrl.Init).toHaveBeenCalled();
   });
});

Solution:

Create the spy on the Original Prototype in the beforeEach function

 beforeEach(function() {
     module('app.main');

     spyOn(UnitTestsCtrl.prototype, 'Init');

     inject(function ($controller) {
        ctrl = $controller('unitTestsCtrl', {});
     });
 });

 it('Init was called on Controller initialize', function () {
        expect(ctrl.Init).toHaveBeenCalled();
 });

回答1:


The way it is, you cannot and you really do not need to as well. The reason you cannot is because you are calling init() on the controller constructor, i.e on instantiation, which happens when you call $controller service to instantiate the controller in your test. So you are setting up spy too late. You probably do not need to, because if the controller is instantiated init method would have been called for sure. But how ever if you are making any specific service/dependency calls inside init, you can spy on those mocks and set up expectations.

Your expectation says: Service Call executed so create a spy for that service and set up expectation.

example:

   var myService = jasmine.createSpyObj('myService', ['someCall']);
   myService.someCall.and.returnValue($q.when(someObj));
   //...


  ctrl = $controller('unitTestsCtrl', {'myService':myService});

and set the expectation on the method someCall of myService.

 expect(myService.someCall).toHaveBeenCalled();

If you really want to spy on init, then you would need to have access to UnitTestsCtrl constructor in the spec and you would need to set spy on its prototype method init before instantiating.



来源:https://stackoverflow.com/questions/28396107/angularjs-unit-test-check-if-init-function-was-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!