2016-06-02 12 views
1

カルマとAngular2には不便な点があります。私はこれを最も単純なデモに減らそうとしました。このタイプのクラスは、インスタンスメンバアプローチと静的メンバアプローチの両方で、できませんSpyOn TypeScript静的メンバーをジャスミンできません

export class Echo { 

    static classLog = console.log; 

    instanceLog = console.log; 

    static classEcho(msg: string) { 
     this.classLog(msg); 
    } 

    instanceEcho (msg: string) { 
     this.instanceLog(msg); 
    } 
} 

...その後、このような単純な純粋な活字体のテスト:

import {Echo} from './echo'; 

var e = new Echo(); 
e.instanceEcho('instanceEcho!'); 
Echo.classEcho('classEcho!'); 

..results中:

instanceEcho! 
classEcho! 

良いジャスミンはそれをキャプチャされていない理由静的メソッドは、適切に実際の作業ではないので

START: 
✔ instanceEcho will invoke 'console.log()' 
LOG: 'test classEcho' 
✖ classEcho will invoke 'console.log()' 

SUMMARY: 
✔ 1 tests completed 
✖ 1 test failed 

FAILED TESTS: 
    ✖ classEcho will invoke 'console.log()' 
     Chrome 50.0.2661 (Mac OS X 10.11.5) 
    Expected spy log to have been called with [ 'test classEcho' ] 
    but it was never called. 

:中

import {it} from '@angular/core/testing'; 
import {Echo} from './echo'; 

describe('Logging',()=> { 
    it('instanceEcho will invoke \'console.log()\'',() => { 
     spyOn(console, 'log'); 
     expect(console.log).not.toHaveBeenCalled(); 
     var e = new Echo(); 
     e.instanceEcho('test instanceEcho'); 
     expect(console.log).toHaveBeenCalledWith('test instanceEcho'); 
    }); 

    it('classEcho will invoke \'console.log()\'',() => { 
     spyOn(console, 'log'); 
     expect(console.log).not.toHaveBeenCalled(); 
     Echo.classEcho('test classEcho'); 
     expect(console.log).toHaveBeenCalledWith('test classEcho'); 
    }); 
}); 

..results:

しかし、ジャスミンから同じことを確認してみてください?

+0

面白いに切り替えた場合の呼び出しをキャッチします...しかし、両方の方法は、 '' classEcho'とinstanceEcho'は同じコードを持っていません。コンテンツ全体を削除して 'console.loge(msg)'だけを呼び出すとどうなりますか?それはその後動作しますか? – iberbeu

+0

私はそれをテストし、それは私のために働いた。あなたの問題は実際には 'this.classLog(msg);メソッドの中にあると思います。 – iberbeu

+0

' instanceEcho'と 'classEcho'の両方が間接化のステップを提供していますが、間接化を取り除き、' console.log '間接指示のポイントは、実行時に異なるロガーを後で割り当てることができるようにすることです。 –

答えて

0

私は今、これは活字体の静的メンバーをスパイジャスミンの問題が、thisへの参照を失うだけで、昔ながらのJavaScriptの問題ではありません実現しています。ジャスミンSpyOnが適切にconsole.log()私は、例えば:

export class Echo2 { 

    static classLogger = console; 
    instanceLogger = console; 

    static classEcho(msg: string) { 
     this.classLogger.log(msg); 
    } 

    instanceEcho (msg: string) { 
     this.instanceLogger.log(msg); 
    } 
} 
関連する問題