2013-01-25 33 views
22

我實際上是JavaScript和Jasmine的新手。所以這可能是一個非常明顯的問題,可以解決我的問題,但我看不到它。Spin on console.error()with Jasmine

我想檢查(加載時)(已存在的)JavaScript應用程序是否調用console.error()。我真的沒有看到如何用Jasmine實現這一點。我已將JavaScript文件以及規格文件包含在SpecRunner.html中。 但我認爲我需要「實例化」應用程序以測試它是否在控制檯上引發任何錯誤,對嗎?

或者是否應該將僅用於此目的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

現在使用'.and.clickThrough();'或'and.callFake(function(){...})'''''實現,而不是使用Jasmine 2.x來完全裸露函數。希望有所幫助。 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()將調用覆蓋函數。