2
votes

I have some problem with unit test in AngularJS. I took from github angular seed app and wrote some modules. And now when i try to test it I have error. Problem is only in unit test - in browser app is working correctly.

I feel that it should be something easy to resolve, but I can't find where I make mistake.

My controller:

'use strict';
angular.module('myApp.student', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/student', {
    templateUrl: 'student.html',
    controller: 'StudentCtrl'
  });
}])
.controller('StudentCtrl', ['$scope', '$http', '$modal', '$log', function($scope, $http, $modal, $log) { ... }]);

My unit test dokumenty_test.js:

describe('myApp.student', function() {
    beforeEach(module('myApp.student'));

  describe('StudentCtrl controller', function(){

    it('should ....', inject(function($controller) {
      //spec body
      var view1Ctrl = $controller(StudentCtrl');
      expect(view1Ctrl).toBeDefined();
    }));

  });
});

And the error from console: Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope http://errors.angularjs.org/1.2.28/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope

Thanks in advance

1

1 Answers

2
votes

You need to manually set up the controllerĀ“s dependencies when creating it:

it('should ....', inject(function($controller, $rootScope, $http, $modal, $log) {

  var view1Ctrl = $controller('StudentCtrl', {
    '$scope': $rootScope.$new(),
    '$http': $http,
    '$modal': $modal,
    '$log': $log
  });

  expect(view1Ctrl).toBeDefined();
}));

Demo: http://plnkr.co/edit/IciIZvjRu66P3NhDc6ud

Note that I added the module ui.bootstrap as a dependency to the app since the controller is using $modal.

You can read more about unit testing controllers here.