AngularJS茉莉服务模拟 [英] AngularJS jasmine service mock

查看:299
本文介绍了AngularJS茉莉服务模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎有几种方法测试使用茉莉花角控制器时,存根出的服务。

There seems to be several ways to stub out services when testing Angular controllers using Jasmine.

有一个问题我已经习惯的方式是做一个beforeEach块以下内容:

One of the ways I've become accustomed to is to do the following in a beforeEach block:

mockService = {}

inject( $controller) ->
  controller = $controller('MyController', {
    MyRealService: mockService
  })

另一种方法是使用 $提供存根我的依赖注入服务:

Another way is to use $provide to stub my dependency injected service:

module('app', ($provide) ->
  mockService = {}
  $provide.value('MyService', mockService)
)

当我有:

afterEach ->
  httpBackend.verifyNoOutstandingExpectation()

在我的测试。只有 $提供方法有效,而 $控制器风格不会。使用 $控制器试验在某种程度上击中 MyRealService ,并包括所有的依赖,而不是忽略,并使用 mockService 。如果没有 verifyNoOutstandingExpectation(),这两种方法似乎有同样的表现,并测试通过。

in my test. Only the $provide method worked, and the $controller style would not. Using $controller the test was somehow hitting MyRealService and including all of its dependencies, rather than ignoring and using mockService. Without the verifyNoOutstandingExpectation(), both methods seem to behave the same and the test passes.

什么是2款的主要区别?当你应该使用一个比其他?任何想法,为什么存根的影响是的presence不同的一个 verifyNoOutstandingExpectation()

What are the main differences between the 2 styles? When should you be using one over the other? Any ideas why the effect of stubbing is different in the presence of a verifyNoOutstandingExpectation()

推荐答案

什么是两种风格之间的主要区别?

在第一种情况下,我们注入了虚假对象自己到控制器,而用第二种方法,我们告诉角度哪里能找到假货时,它需要后注入他们。

In the first case, we inject our fake objects ourselves into the controller, whereas with the second method we tell Angular where it can find the fakes when it needs to inject them later.

当你应该使用一个比其他?

我preFER,因为它是比较明显的,特别是当我们测试控制器,它是足够的第一种方法。

I prefer the first method as it is more obvious, and especially when we test controllers, it is sufficient.

我的服务/工厂或路由测试打交道时大多使用 $提供方法。由于服务不能newed了之类的控制器,我们需要欺骗注入功能使用提供使用我们的假货。

I mostly use the $provide method when dealing with services/factories or routing testing. Since services can't be "newed up" like controllers, we need to trick the inject function to use our fakes using the provider.

和测试路由的情况下,我们没有其他的可能性比使用提供存根出在路由解析器使用的服务。

And in the case of testing routing we have no other possibility than using the provider to stub out the services used in the route resolvers.

任何想法,为什么存根的效果是在verifyNoOutstandingExpectation()

如何回答这个不能确定,但​​我发现 $ httpBackend 来不那么明显的使用。尤其是测试路由时。它记录所有流量,包括像呼叫路由中等等,这使得它很容易忽视在设置呼叫定义的模板。

Not really sure on how to answer this one, but I have found $httpBackend to be not-so-obvious to use. Especially when testing routes. It records all traffic, including things like calls to templates defined in a route etc, which makes it very easy to overlook a call in the setup.

这篇关于AngularJS茉莉服务模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆