【问题标题】:Karma: ReferenceError: app is not defined业力:ReferenceError:应用程序未定义
【发布时间】:2014-08-25 13:00:00
【问题描述】:

我按照 http://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-karma.html 的教程使用 Karma 测试 AngularJS 应用程序。

我的 karma.conf.js 看起来像这样:

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: [
      'public/bower_components/angular/angular.min.js',
      'public/bower_components/angular-route/angular-route.min.js',
      'public/bower_components/d3/d3.js',
      'public/bower_components/nvd3/nv.d3.js',
      'public/bower_components/angularjs-nvd3-directives/dist/angularjs-nvd3-directives.js',
      'public/bower_components/angular-mocks/angular-mocks.js',
      'public/scripts/**/*.js',
      'test/*Spec.js'
    ],
    exclude: [
    ],
    preprocessors: {
    },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};

我的测试:

describe("app", function() {

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

  it('should have a HomeController', function() {
    expect(app.HomeController).not.to.equal(null);
  });

});

public/scripts/app.js

angular.module('app', [
  'ngRoute',
  'app.controllers',
  'nvd3ChartDirectives'
]);

我在控制台中得到一个输出:应用程序应该有一个 HomeController FAILED ReferenceError: 应用未定义

任何帮助将不胜感激,

提前致谢!

【问题讨论】:

  • 我认为您的模块app 是在app.js 中定义的。你能显示使用代码吗?也许您想将 'public/scripts/*.js', 更改为 'public/scripts/**/*.js', 以便每个子目录都包含在您的测试中
  • 更新了问题,但得到了相同的输出。
  • 您的基本路径必须指向您的应用程序脚本所在的位置。我们的在 /app 中,因此定义了基本路径和 ../app

标签: angularjs unit-testing karma-runner karma-mocha


【解决方案1】:

解决方法:

describe('app', function(){
  beforeEach(module('app'));

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

  it('should have defined HomeController', function() {
    expect(ctrl).toBeDefined();
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-17
    • 2019-12-31
    • 2018-03-05
    • 2021-06-04
    • 2017-11-08
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    相关资源
    最近更新 更多