Angular JS Test driven Development with multiple controllers Angular JS Test driven Development with multiple controllers angularjs angularjs

Angular JS Test driven Development with multiple controllers


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.


You can inject any controller with the $controller service, e.g.

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

see docs here:https://docs.angularjs.org/api/ngMock/service/$controller

so what you do is inject that controller first, then your other controller. then the first controller will have been instantiated at the time the second gets instantiated.


I am new to angular, it seems to be possible to inject multiple controllers at once. However best practice is to generate a mock controller that behaves as you expect the second controller to behave. This reduces the number of things you are testing at once. The following link may be helpful for creating a mock controller, http://www.powdertothepeople.tv/2014/08/28/Mocking-Controller-Instantiation-In-AngularJS-Unit-Test/ .