2013-01-25 6 views
22

私はJavaScriptとJasmineを実際に使っていません。だから私の問題を解決するのは本当に明白なことかもしれませんが、私はそれを見ることはできません。ジャスミンでconsole.error()を盗んでいる

JavaScriptアプリケーションがロード中にconsole.error()を呼び出すかどうかを確認したいと思います。私は本当にジャスミンでこれを実現する方法を見ていない。私はSpecRunner.htmlにJavaScriptファイルとspecファイルを含めました。 しかし、コンソールに何らかのエラーが発生したかどうかをテストするために、アプリケーションを「インスタンス化」する必要があるのですか?

または、この目的のためにのみSpecRunner.htmlコードをアプリのHTMLコードに含める必要がありますか?

答えて

38

あなたはこのようconsole.errorをスパイすることができます

beforeEach(function(){ 
    spyOn(console, 'error'); 
}) 

it('should print error to console', function(){ 
    yourApp.start(); 
    expect(console.error).toHaveBeenCalled(); 
}) 
+0

を使用うん、それは私が想定したものです。しかし、これでは成立しません。アプリの仕組みと関係があるかもしれません。しかし、助けてくれてありがとう! – Christian

+0

申し訳ありませんが、私はもう一度チェックし、いくつかの微調整を行い、それは働いた。私が必要としていたのは、これが実際に働くべきであるという保証だったと思う。再度、感謝します! – Christian

+1

Jasmine 2.xを使用して関数nakedを残すのではなく、 '.and.clickThrough();'または 'and.callFake(function(){...});希望が役立ちます。 C§ – CSS

0

あなたはこのように標準console.error関数をオーバーライドすることができます

//call the error function before it is overriden 
console.error('foo'); 

//override the error function (the immediate call function pattern is used for data hiding) 
console.error = (function() { 
    //save a reference to the original error function. 
    var originalConsole = console.error; 
    //this is the function that will be used instead of the error function 
    function myError() { 
    alert('Error is called. '); 
    //the arguments array contains the arguments that was used when console.error() was called 
    originalConsole.apply(this, arguments); 
    } 
    //return the function which will be assigned to console.error 
    return myError; 
})(); 

//now the alert will be shown in addition to the normal functionality of the error function 
console.error('bar'); 

このソリューションは、ジャスミンや他の何かで動作します。上のコードを他のコードの前に置くと、これ以降の呼び出しはconsole.error()にオーバーライドされた関数を呼び出します。

関連する問題