【问题标题】:Mock up an angular module so a factory can be tested模拟一个角度模块,以便可以测试工厂
【发布时间】:2014-01-15 13:45:57
【问题描述】:

我正在尝试在不依赖我的应用程序模块的情况下对服务进行单元测试。这应该如何工作?

代码:

#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 模块的真实实例。

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

【问题讨论】:

  • 你想做什么来明确需要访问模块本身?
  • 我不需要访问该模块,但我希望我的工厂能够自行创建。更新为使用示例的实际预期用途。

标签: angularjs coffeescript jasmine karma-runner


【解决方案1】:

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

  1. 加载 angular + angular 插件
  2. 加载依赖模块定义(例如:myApp)。这是我错过的。
  3. 加载文件进行测试
  4. 加载规范
  5. 让测试规范实例化依赖模块和被测注入

这是一个有效的设置:

#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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    相关资源
    最近更新 更多