SquarePeg
SquarePeg

Reputation: 1781

AngularJS Karma Jasmine Error: Cannot Read Property of Undefined

This is my first attempt at using Karma/Jasmine. I want to use it to test an AngularJS app.

This is just a simple Hello World test to make sure things are working but they are not.

I am trying to test a controller called InboxController. I have defined a scope variable: $scope.greeting = 'Hello World'.

I am trying to test that in a separate file called controllers-test.js.

This is the test:

'use strict';

describe('Controllers Tests ', function () {

describe('InboxController', function () {
    var scope;

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

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

    }));

    it('should return Hello World', function () {
        expect(scope.greeting).toBe('Hello World');
    });
});

});

I keep getting an error:

Cannot read property 'greeting' of undefined, which relates back to scope.greeting in the test code.

Karma config:

files : [

            'bower_components/angular/angular.js',
            'bower_components/angular-mocks/angular-mocks.js',
            'bower_components/angular-resource/angular-resource.js',
            'app.js',
            'js/*.js',
            'test/*.js'
             ],

InboxController:

app.controller('InboxController', function($rootScope, $scope,
    $location, InboxService) {

$scope.greeting = 'Hello World';

$rootScope.loggedIn = true;

// Load Inbox
$scope.loadInbox = function() {

    $scope.emails = InboxService.getMessages().success(function(jsonData) {

        $scope.emails = jsonData;
    });
}

// Delete email
$scope.delete = function (id) {
    InboxService.delete(id).success(function() {

        $scope.loadInbox();
    });
};

$scope.loadInbox();

});

Upvotes: 4

Views: 13061

Answers (1)

SquarePeg
SquarePeg

Reputation: 1781

Solved the issue myself. I needed to reference all the angular dependencies in the karma config file:

files : [

            'bower_components/angular/angular.js',
            'bower_components/angular-route/angular-route.js',
            'bower_components/angular-sanitize/angular-sanitize.js',
            'bower_components/angular-cookies/angular-cookies.js',
            'bower_components/angular-bootstrap/ui-bootstrap.js',
            'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
            'bower_components/angular-mocks/angular-mocks.js',
            'bower_components/angular-resource/angular-resource.js',
            'app.js',
            'js/*.js',
            'test/*.js'
             ],

It is important that this one comes first:

bower_components/angular/angular.js

Upvotes: 2

Related Questions