在我的angular 2应用程序中,如何测试我的main方法中的外部方法(依赖项)是否被相应调用。
例如,
Class ServiceA
{
constructor(
private serviceB : ServiceB
){}
//How do I test this method to make sure it does what it should ?
mainMethod()
{
//External method
this.serviceB.otherMethod();
this.sideMethod();
}
sideMethod()
{
//Do something
}
}
Class ServiceB
{
constructor(){}
otherMethod()
{
//Do something
}
}
这是我到目前为止所尝试的内容
it('On otherMethod returns false, do something',
inject([ServiceA, ServiceB], (serviceA: ServiceA, serviceB: ServiceB) => {
spyOn(serviceB, 'otherMethod').and.returnValue(false);
spyOn(serviceA, 'sideMethod');
spyOn(serviceA, 'mainMethod').and.callThrough();
expect(serviceB.otherMethod()).toHaveBeenCalled();
expect(serviceA.sideMethod()).toHaveBeenCalled();
expect(serviceA.mainMethod()).toHaveBeenCalled();
}));
从上面的代码中,我收到一条错误说明
找不到要监视otherMethod()
的对象
这里有什么问题?
答案 0 :(得分:0)
您必须传递间谍serviceB.otherMethod
的功能参考。您目前正在通过调用serviceB.otherMethod()
来调用间谍,这将返回otherMethod
的返回值,而不是间谍。
it('On otherMethod returns false, do something',
inject([ServiceA, ServiceB], (serviceA: ServiceA, serviceB: ServiceB) => {
spyOn(serviceB, 'otherMethod').and.returnValue(false);
spyOn(serviceA, 'sideMethod');
spyOn(serviceA, 'mainMethod').and.callThrough();
// Notice spy reference here instead of calling it.
expect(serviceB.otherMethod).toHaveBeenCalled();
expect(serviceA.sideMethod).toHaveBeenCalled();
expect(serviceA.mainMethod).toHaveBeenCalled();
}));
Jasmine文档:https://jasmine.github.io/2.0/introduction.html#section-Spies