Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Angular Test failing ($injector:unpr Unknown Provider) when I have no dependencies

I'm getting this error. It's something along the lines of me injector being unable to resolve a required dependency, but even with my limited knowledge of angular I'm pretty sure this code shouldn't be depending on any modules.

This code works perfectly fine in the browser, however it doesn't seem to want to work in my test. I've been following the examples from the documentation

My angular version is 1.2.13 (edit: now using 1.12.15).

Here's my code:

var app = angular.module('app', [])

.controller('GreetingCtrl', function ($scope) {
  $scope.title = "Hello World!";
  $scope.message = "Test, test. One? Two?";
});

Here's the jasmine test that's failing.

describe('app controllers', function () {
  beforeEach(module('app'));

  describe('GreetingCtrl', function () {
    it('should says hello world', inject(function ($controller) {
      var $scope = {};
      $controller('GreetingCtrl', $scope);
      expect($scope.title).toBe("Hello World!");
    }));
  });
});

I don't believe it's even gotten to the point of running my test because it fails before even running it. I believe I've correctly concatenated the files correctly as well. Here's the error I've received from the jasmine test runner.

Error: [$injector:unpr] http://errors.angularjs.org/1.2.13/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope (line 4569) (1)

Edit: tried upgrading to 1.12.15, nothing has changed.

like image 751
akst Avatar asked Mar 29 '14 05:03

akst


1 Answers

So apparently after a little chat on the IRC, the documentation might be out of date, & this is a working solution. I was linked to this solution, & corrected my test accordingly.

describe('app controllers', function () {
  var ctrl, scope;

  beforeEach(module('app'));

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

    it('should says hello world', function () {
      expect(scope.title).toBe("Hello World!");
    });
  });
});

Edit:

I accidentally misread the docs originally & here's a cleaner solution closer to the docs.

describe('app controllers', function () {
  beforeEach(module('app'));

  describe('GreetingCtrl', function () {
    it('should says hello world', inject(function ($controller) {
      var $scope = {};
      // this is the line that caused me pain
      $controller('GreetingCtrl', { $scope: $scope }); 
      expect($scope.title).toBe("Hello World!");
    }));
  });
});
like image 178
akst Avatar answered Oct 24 '22 01:10

akst