【问题标题】:Jasmine/Karma not finding Angular modulesJasmine/Karma 找不到 Angular 模块
【发布时间】:2014-09-21 10:44:51
【问题描述】:

我正在尝试使用 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();
    };
});

test-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);
    });
});

错误信息: 错误:[ng:areq] 参数 'TestCtrl' 不是函数,未定义

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

我错过了什么?

【问题讨论】:

  • 应该是beforeEach(module('app'))。看起来您也忘记将 ngAnimate 添加到 karma 文件配置中:files: ['lib/angular.js', 'lib/angular-route.js', 'lib/angular-mocks.js', ...].
  • 这就解决了!我想知道为什么示例中没有提到模块('app')...谢谢!

标签: angularjs karma-jasmine


【解决方案1】:

我可以看到两个问题。在描述部分必须有主模块注入:

beforeEach(module('app'));

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

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-01-14
  • 2018-03-19
  • 2018-12-28
  • 1970-01-01
  • 2015-12-06
  • 2017-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多