我有一个由不同 Controller 使用的 Angular 服务。它包含一个需要任何 Controller 实例作为参数的方法。
myService.methodAbc( ctrl );
我知道如何为该服务设置 Jasmine 规范,但在我的规范中设置一个假 Controller 以便我可以测试所述方法时,我不知所措。使用应用程序的现有 Controller 之一感觉不对,因为如果我重命名/更改/删除 Controller ,我的服务测试就会中断。
如有任何意见,我们将不胜感激。我感觉我在这里遗漏了一些明显的东西。
最佳答案
您可以传入一个普通的旧对象来充当假 Controller 。就我个人而言,我更喜欢使用 SinonJS为方法创建 stub ,因为它将允许您的测试断言 myService
如何与 ctrl
交互。 Jasmine 有它自己的假对象方法,我不熟悉,你也可以使用。这是使用SinonJS ( and a library which integrates it with Jasmine ) 时的样子:
var fakeController = {
someMethod: sinon.stub(),
anotherMethod: sinon.stub()
};
myService.methodAbc(fakeController);
expect(fakeController.someMethod).toHaveBeenCalledWith('foo', 'bar');
更新:
以下是如何使用 native Jasmine 库来执行相同操作:
var fakeController = jasmine.createSpyObj(
'fakeController',
['someMethod', 'anotherMethod']);
myService.methodAbc(fakeController);
expect(fakeController.someMethod).toHaveBeenCalledWith('foo', 'bar');
关于javascript - 测试 Angular 服务时,我如何使用该服务模拟 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21583867/