模拟角度模块,以便测试工厂

时间:2013-12-28 00:19:14

标签: angularjs coffeescript jasmine karma-runner

我正在尝试对服务进行单元测试,而不依赖于我的应用程序模块。这应该如何运作?

代码:

#karma.conf.coffee
files: [
  'bower_components/angular/angular.js'   # angular core
  'bower_components/**/angular-*.js'      # all angular plugins
  'utils/typometer.js'
  'utils/typometer.spec.js'
]

# utils/typometer.coffee
angular.module('myApp').factory 'typometer', ->
  @sizes =
    'A':8
    'B':9
  @ # return `this`

# utils/typometer.spec.coffee
describe 'typometer', ->
  typometer = undefined # scope control
  # Create a mock module so that the typometer factory has something to attach to
  beforeEach angular.mock.module 'myApp' #TODO: why doesn't mock.module work?
  # Inject the typometer service
  beforeEach angular.mock.inject (_typometer_) ->
    typometer = _typometer_ # http://docs.angularjs.org/api/angular.mock.inject

  it 'exists', ->
    expect(typometer).toBeDefined() # fail. 'Uncaught Error: [$injector:nomod] Module 'coatue' is not available!'
    expect(typometer.sizes.A).toEqual 8

最终目标是能够实例化typometer服务并单独测试它,而无需站立myApp模块的实际实例。

我认为这是某种操作顺序问题。当声明typometer工厂时,该模块不存在 - 我想测试我的生产文件。在加载任何测试文件之前,我是否必须创建一个shell应用程序或加载真实应用程序?这是我想从测试考虑中删除的依赖项。

1 个答案:

答案 0 :(得分:2)

我想我现在明白了。对于工作设置,需要执行以下所有操作:

  1. 加载角度+角度插件
  2. 加载相关模块定义(例如:myApp)。这就是我错过的。
  3. 加载要测试的文件
  4. 加载规格
  5. 让测试规范实例化受测试的依赖模块和注射剂
  6. 这是一个有效的设置:

    #karma.conf.coffee
    files: [
      'bower_components/angular/angular.js'   # angular core
      'bower_components/**/angular-*.js'      # all angular plugins
          'main.js'                               # still need to load the app definition
      'utils/typometer.js'
      'utils/typometer.spec.js'
    ]
    
    # utils/typometer.coffee
    angular.module('myApp').factory 'typometer', ->
      @sizes =
        'A':8
        'B':9
      @ # return `this`
    
    # utils/typometer.spec.coffee
    describe 'typometer', ->
      typometer = undefined # scope control
      beforeEach ->
        angular.mock.module 'myApp' # instantiate the mock app
        angular.mock.inject (_typometer_) -> # instantiate the mock service
          typometer = _typometer_ # http://docs.angularjs.org/api/angular.mock.inject
    
      it 'exists', ->
        expect(typometer).toBeDefined()
        expect(typometer.sizes.A).toEqual 8