首页 文章

Jasmine / Karma没有找到Angular模块

提问于
浏览
3

我正在尝试使用Jasmine和Karma进行单元测试,但由于某种原因,我的Angular模块无法找到 . 我修改了示例中的代码:

karma.config.js:

files: [
  'lib/angular.js',
  'lib/angular-mocks.js',
  'js/app.js',
  'js/controllers.js',
  'js/factories.js',
  'tests/**/*.js'
]

app.js:

var app = angular.module('app', ['ngRoute']);
app.config(function ($routeProvider) {
  $routeProvider
    .when('/test', {
      templateUrl: 'views/test.html',
      controller: 'TestCtrl'
    })
    .otherwise({redirectTo: '/'});
});

controllers.js:

app.controller('TestCtrl', function ($scope, $location) {
    console.log('Test Controller');
    $scope.isActive = function(route) {
        return route === $location.path();
    };
});

测试spec.js:

describe('TestCtrl testing', function () {
    var scope, $location, createController;

    beforeEach(inject(function ($rootScope, $controller, _$location_) {
        $location = _$location_;
        scope = $rootScope.$new();

        createController = function () {
            return $controller('TestCtrl', {
                '$scope': scope
            });
        };
    })); 

    it('should...', function () {
        var controller = createController();
        $location.path('/test');
        expect($location.path()).toBe('/test');
        expect(scope.isActive('/test')).toBe(true);
        expect(scope.isActive('/contact')).toBe(false);
    });
});

错误消息: Error: [ng:areq] Argument 'TestCtrl' is not a function, got undefined

我也试过: beforeEach(module('TestCtrl')) ,但它没有帮助 .

我错过了什么?

1 回答

  • 3

    我可以看到两个问题 . 在describe部分中必须有主模块注入:

    beforeEach(module('app'));
    

    第二个问题是你忘了将ngAnimate模块添加到Karma文件配置数组:

    files: [
        'lib/angular.js', 
        'lib/angular-route.js', // <-- this guy
        'lib/angular-mocks.js', 
        ...
    ]
    

相关问题