AngularJS Karma Jasmine 错误:无法读取未定义属性

4

这是我第一次尝试使用Karma/Jasmine,我想用它来测试一个AngularJS应用。

这只是一个简单的Hello World测试,以确保一切正常,但事实并非如此。

我正在尝试测试一个名为InboxController的控制器。我已经定义了一个作用域变量:$scope.greeting = 'Hello World'。

我正在尝试在一个名为controllers-test.js的单独文件中进行测试。

这是测试内容:

'use strict';

描述('控制器测试', 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');
    });
});

我会尽力为您翻译,以下为您需要翻译的内容:

我一直收到一个错误信息:

无法读取未定义的属性'greeting',这与测试代码中的scope.greeting有关。

Karma配置:

});

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();

});

1个回答

2

我自己解决了这个问题。我需要在karma配置文件中引用所有的angular依赖项:

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'
             ],

重要的是要先处理这个:

bower_components/angular/angular.js

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接