【问题标题】:How to mock AngularJS $resource with $promise.then in jasmine specs如何在茉莉花规范中使用 $promise.then 模拟 AngularJS $resource
【发布时间】:2015-05-27 21:35:00
【问题描述】:

我使用$resource设置了一些API调用,在测试时我采用了注入$q然后做的通用方法

mockMyService.doSomethingAsync.andReturnValue($q.when(successResponse))

这已经很好了,但是,我有一个如下所示的方法:

# MyService
MyService.doSomethingAsync(params).$promise.then ->
    $scope.isLoading = false

# MyService Spec
mockMyService = 
  doSomethingAsync: jasmine.createSpy('doSomethingAsync')

it 'calls service #doSomethingAsync', ->
  inject ($q) -> mockMyService.doSomethingAsync.and.returnValue($q.when(response))
  controller.methodThatWrapsServiceCall()
  scope.$apply()

  expect(mockMyService.doSomethingAsync).toHaveBeenCalled()

不幸的是,当$promise.then 最后被链接时,上述模拟策略似乎不起作用。我最终得到以下错误:

TypeError: 'undefined' is not an object (evaluating 'MyService.doSomethingAsync(params).$promise.then')

doSomethingAsync().$promise 结尾的方法使用此模拟策略通过测试没有问题。

(其他信息:这些是使用 Karma 和 PhantomJS 运行的 Jasmine 测试)

【问题讨论】:

    标签: angularjs unit-testing jasmine promise


    【解决方案1】:

    其实,想通了!

    我刚刚更改了我的模拟以返回 and.returnValue( { $promise: $q.when(response) } )

    【讨论】:

      猜你喜欢
      • 2016-06-08
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 2020-05-07
      • 1970-01-01
      相关资源
      最近更新 更多