简体   繁体   English

测试Angular服务时,如何使用该服务模拟控制器?

[英]When testing an Angular service, how would I mock a controller using that service?

I have an Angular service that is used by different controllers. 我有一个由不同控制器使用的Angular服务。 It contains a method that expects any controller instance as argument. 它包含一个以任何控制器实例为参数的方法。

myService.methodAbc( ctrl );

I know how to set up the Jasmine specs for the service but I am at a loss when it comes to setting up a fake controller in my specs so I can test said method. 我知道如何设置该服务的Jasmine规范,但是在我的规范中设置假控制器时,我很茫然,因此我可以测试所述方法。 Using one of the app's existing controllers feels wrong as my service's test would break were I to rename/change/delete the controller. 使用应用程序现有的控制器之一感觉不对,因为如果我重命名/更改/删除控制器,我的服务测试就会中断。

Any input would be appreciated. 任何输入将不胜感激。 I have the feeling I am missing something obvious here. 我觉得我在这里想不到一些明显的东西。

You can pass in a plain-old object to act as a fake controller. 您可以传入一个普通的对象来充当伪控制器。 Personally, I prefer to use SinonJS to create stubs for methods, because it will allow your test to assert how, say, myService interacts with ctrl . 就我个人而言,我更喜欢使用SinonJS为方法创建存根,因为它将允许您的测试断言myService如何与ctrl交互。 Jasmine has its own fake object methods, which I am not familiar with which you can use as well. Jasmine有自己的伪对象方法,我也不熟悉,您也可以使用它们。 Here's how it would look when using SinonJS ( and a library which integrates it with Jasmine ): 使用SinonJS( 以及将其与Jasmine集成的库)时的外观如下:

var fakeController = {
    someMethod: sinon.stub(), 
    anotherMethod: sinon.stub() 
};
myService.methodAbc(fakeController);

expect(fakeController.someMethod).toHaveBeenCalledWith('foo', 'bar');

Update: 更新:

Here's how you can use the native Jasmine library to do the same: 这是使用本地Jasmine库执行相同操作的方法:

var fakeController = jasmine.createSpyObj(
    'fakeController', 
    ['someMethod', 'anotherMethod']);

myService.methodAbc(fakeController);

expect(fakeController.someMethod).toHaveBeenCalledWith('foo', 'bar');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM