【问题标题】:Unknown provider in test case for angular with es6 module带有 es6 模块的 Angular 测试用例中的未知提供者
【发布时间】:2025-11-28 10:45:02
【问题描述】:

我必须为控制器编写 karma-jasmine 测试用例

(->

class AddUserController
  @$inject = ['$scope', '$http', '$state', 'UserFactory']

  constructor: (@$scope, @$http, @$state, UserFactory) ->
    @user = new UserFactory()



angular
.module('app', [])
.controller('AddUserController', AddUserController)
)()

但是当我在测试用例中注入 AddUserController 时,它给了我未知的提供者:

describe('add_user_controller', function() {
  var addUserController, $httpBackend;

  beforeEach(module("app"));

  beforeEach(
    inject( function($injector, $rootScope) {
      addUserController = $injector.get('AddUserController')
    })
  );
  it('should have initialize values', function() {
    expect(addUserController.user).toBeDefined();
  })
});

谁能猜到,这里出了什么问题。

这里是 karma.conf.js 代码

module.exports = function(config) {
  config.set({
    frameworks: ['jasmine'],
    files: [
      'node_modules/angular/angular.js',
      'node_modules/angular-mocks/angular-mocks.js',
      '*.coffee',
      'test/*.coffee'
    ],
    preprocessors: {
      '*.coffee': ['coffee']
    },
    plugin: [
      'karma-coffee-preprocessor',
      'karma-jasmine',
      'karma-chrome-launcher',
    ],
    autoWatch: true,
    browsers: ['Chrome']
  });
};

我的 addUserController.coffee 和 karma.conf.js 位于同一根(级别)上。

【问题讨论】:

    标签: angularjs unit-testing karma-jasmine


    【解决方案1】:

    您应该通过将控制器名称传递给$controller 服务来获取控制器实例。如下所示

    scope = $rootScope.$new(true);
    //inject `$controller` before use it.
    addUserController = $controller('AddUserController', { $scope: scope });
    

    【讨论】:

    • 现在它给出错误无法读取未定义的属性'$scope':(
    • 我也试过写 addUserController = $controller('AddUserController', {$scope: scope, $http: $http, $state: $state, UserFactory: userFactory}) 没有运气。
    • 参数 'AddUserController' 不是函数,未定义
    • 在页面上是否有 ypu 引用了控制器脚本。同时也引用了所有相关的 Angular 文件
    • 您必须参考AddUserController.js + 其他您要测试的角度组件文件和已定义应用程序的文件