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

上記のコードから、試してみたものだ、私はというエラーを得た

にオブジェクトを見つけることができませんでした

spy on otherMethod()

ここで何が間違っていますか?

答えて

0

あなたのスパイの関数リファレンスを渡す必要がありますserviceB.otherMethod。あなたは現在、スパイの代わりにotherMethodの戻り値を返すserviceB.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

を私はこの質問、おかげでとにかく男を投稿分後にそれを考え出しました! –

関連する問題