Search code examples
angularjsjasmineangular-mock

Check $scope variable with jasmine return error


Currently trying to check very simple angular variables and functions. I cannot get even the simplest to work. This is my first time using it, and I need to use the older version as my lecturer requires it.

In the app.js I have many controllers but im only starting with one controller, with one variable assigned to a string:

var app = angular.module('myApp', ['ngRoute']);
blah blah blah etc etc

app.controller('HomeController', function ($scope) {
 $scope.name = 'Batman';
}

In the runner.html file I have the following:

<script src="lib/jasmine-2.2.0/jasmine.js"></script>
<script src="lib/jasmine-2.2.0/jasmine-html.js"></script>
<script src="lib/jasmine-2.2.0/boot.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src='https://code.angularjs.org/1.4.8/angular-mocks.js'></script>

<!-- include source files here... -->
<script src="../js/main.js"></script>

<!-- include spec files here... -->
<script src="spec/test.js"></script>

In the test.js i have the following:

describe('myApp', function () {
  var scope, controller;

  beforeEach(angular.mock.module('myApp'));

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

  it('sets the name', function () {
    expect(scope.name).toBe('Batman');
  });
});

I then get the following error when I run the test: Error: [$injector:modulerr]

EDIT

It appears to be the angular routing causing the problem. When I removed the route module 'ngRoute' it appears to function correctly. Is there is method to using jasmine with routing?


Solution

  • The problem with this was you were not having angular-route library included despite having it as a module dependency (angular.module('myApp', ['ngRoute'])).

    I added as the following along with other libraries:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-route.min.js"></script>
    

    And it's working!

    Here's working plunker