title: Unit-testing two controllers with Jasmine in AngularJS
body: <p>I'm writing my first Unit Tests with Jasmine in AngularJS. I already have some controllers, services etc. and am trying to verify them (I know: First testing, then writing the code, but as I said, I am new to unit tests and want to develop my app further with unit tests).</p>
  
  <p>In my case, I have the view with two controllers like</p>
  
  <pre><code>&lt;div ng-controller="firstCtrl"&gt;
    &lt;div ng-controller="secondCtrl"&gt;&lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>On every page-load I check the routeParameters and get data from a WebAPI (this is done by the first controller). My second controller is based on the data, which is set by the first Ctrl to the $scope. </p>
  
  <p>My question is, how do I write my unit-test for the secondCtrl in an elegant way? I have also a third, fourth [...] Controller, which depend on the data which was set by the first Controller. I don't want to have duplicated code, if not necessary.</p>
  
  <p>The second Controller:</p>
  
  <pre><code>angular.module("myApp.controllers.secondController", ["myApp.Model"])
      .controller("secondController", function ($scope, Model) {
          $scope.data.Model = Model;
  
          $scope.doSomething = function () {
              // tries to grab something from the scope, which would normally be set by the first Controller, e.g.
              return $scope.firstCtrlData.x;
          };
      });
  </code></pre>
  
  <p>The spec-file:</p>
  
  <pre><code>   describe('My App', function () {
          beforeEach(angular.mock.module('myApp'));
  
          describe("Controller", function () {
              var controller, scope;
  
              beforeEach(inject(function ($rootScope,  $controller, _Model_) {
                  scope = $rootScope.$new();
  
                  controller = $controller("secondCtrl", {
                      scope: $scope,
                      Model: _Model_
                  });
              }));
  
  
              it('ensures that Model is in scope.data defined', function () {
                  expect($scope.data.Model).toBeDefined();
              });
  
              it('doSomething() does something', function () {
                  var x = $scope.doeSomething();
                  expect(x).toBeDefined();
                  // this will fail
              });
          });
      });
  </code></pre>
  
  <p>It is not just one 'x' - Value, it will be a whole data structure given in json Code, so it probably isn't the best way just by putting all my data in a mocked scope object...</p>
  
  <p>As I am also new to angular, it is probably not even the best approach for the whole app having two controllers, but for me it seemed to be the shortest and most effective variant.</p>