问题描述
我用 $资源
来设置一些API调用,虽然测试中,我都采用注射的一般方法 $ Q
,然后做
I use $resource
to set up some API calls, and while testing I have adopted the general approach of injecting $q
and then doing
mockMyService.doSomethingAsync.andReturnValue($ q.when(successResponse))
此已经工作了pretty好,但是,我有一个类似如下的方法:
This has been working out pretty well, however, I have a method that looks like the following:
# 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
末被链接。我结束工作与以下错误:
and unfortunately the mocking strategy outlined above doesn't seem to work when a $promise.then
is chained at the end. I end up with the following error:
TypeError: 'undefined' is not an object (evaluating 'MyService.doSomethingAsync(params).$promise.then')
中的方法简单地用结束doSomethingAsync()。$承诺
通过测试,而无需使用这种嘲讽的战略问题。
Methods that simply end with doSomethingAsync().$promise
pass the tests without issues using this mocking strategy.
(其他信息:这是茉莉花测试,因果报应和PhantomJS运行)
(Other info: These are Jasmine tests run with Karma and PhantomJS)
推荐答案
其实,想通了!
我只是改变了我的模拟返回 and.returnValue({$承诺:$ q.when(响应)})
I just changed my mock to return and.returnValue( { $promise: $q.when(response) } )
这篇关于如何嘲弄与$ promise.then茉莉规格AngularJS $资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!