2017-03-23 39 views
2

在我的角2应用程序,我如何测试如果我的主要方法内的外部方法(依赖项)被调用相应。茉莉花间谍方法,调用外部方法(角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(); 
    })); 

从上面的代码中试过,我得到了一个错误,说明

找不到一个对象窥探其他方法()

这里有什么问题?

回答

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(); 
})); 

茉莉花文档:https://jasmine.github.io/2.0/introduction.html#section-Spies

+0

我想通了我几分钟后这个问题,还是要谢谢你的人了! –