在我的 angular 2 应用程序中,如何测试我的主方法中的外部方法(依赖项(是否被相应地调用。
例如
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(( 的对象
这是怎么回事?
你必须传递你的间谍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();
}));
茉莉花文档:https://jasmine.github.io/2.0/introduction.html#section-Spies