Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS Test driven Development with multiple controllers

I have developed an web application using Angular JS. I am getting few additional CR which needs to implemented in using TTD approach. We have return unit test cases using Jasmine and Karma. The challenge currently we face is when we try to write unit test case for multiple controllers. I have a main page return on Home Controller & its has an broadcast event in another controller. When i write a unit test case Object for the controller which has this broadcast event is not initialized.

Is there any way to inject the second controller as a dependent object. Answers with Reference Sample link or demo code is much appreciated.

like image 676
Vasanthan Avatar asked Jan 12 '16 11:01

Vasanthan


1 Answers

You state you are using Jasmine and Karma so I assume you are unit testing. If you are "unit" testing you should test each controller individually while mocking, spy, all injected services.

    beforeEach(inject(function ($rootScope, $controller) {
        rootScope = $rootScope;
        scope = $rootScope.$new();
        controller = $controller('MyCtrl as ctrl', {
            '$scope': scope
        });            
    }));

    it('', function(){

     //Arrange
     controller.counter = 0; // Your controller is listening on scope.$on to update this counter.

     //Act
     rootScope.$broadcast('xyz', {});

     //Assert
     expect(controller.counter == 1).toBe(true);
     rootScope.$broadcast('xyz', {});
     expect(controller.counter == 2).toBe(true);
     rootScope.$broadcast('xyz', {});
     expect(controller.counter == 3).toBe(true);
    });

Just be careful with broadcast. Only a domain events (model updated/deleted/created), or something global (signin,signout) should travel over $broadcast. Otherwise, it should be replaced with a service + directive. An example is angular material https://material.angularjs.org/latest/api/service/$mdDialog that is 1 directive with a backing service that can be open/closed from anywhere.

like image 57
Leblanc Meneses Avatar answered Sep 28 '22 19:09

Leblanc Meneses