2010-02-16 21 views
8

我的JavaScript代碼中有以下代碼。JavaScript如何模擬確認方法

if (window.confirm('Are you sure?')) { 
    AdminData.actOnResult('delete'); 
} 

我正在爲這段代碼編寫測試。我如何模擬window.confirm方法?我嘗試了下面的代碼,但沒有奏效。

window.confirm = function(arg) { 
    return true; 
}; 

我可以將window.confirm方法移動到另一個函數,然後我可以嘲笑該方法。不過,我想知道是否有更好的解決方案。

回答

1

你自己的代碼在IE中對我很好。就在在全球範圍內以下應該重寫它:

var confirm = function() { return true; } 

編輯
我已經在過去見過這麼幾個問題,關於嘗試重寫confirm,主要是因爲他們不喜歡它(和誰?)。如果您因爲這種原因試圖繞過它,我建議您考慮更改代碼以實現基於回調的替換以確認。看看jQuery UI's modal confirm就是一個很好的例子。

1

我想在窗口(或其他)對象上實現一個包裝靜態方法的包裝。然後提供你的包裝到任何使用靜態方法。顯然,如果您使用基於「類」的實現,這會更容易。然後,爲了模擬該方法,只需提供一個不同的包裝器即可返回所需的值。

var windowWrapper = { 
    confirm: function(msg) { return confirm(msg); }, 
    ... 
}; 

var mockWrapper = { 
    confirm: function(msg) { return true; }, 
    ... 
} 

var wrapper = windowWrapper; 
if (test) { 
    wrapper = mockWrapper; 
} 

...

if (wrapper.confirm('Are you sure?')) { 
    AdminData.actOnResult('delete'); 
} 
3

我使用茉莉花的單元測試,並嘲笑警報並用以下

alert = function (alertString) {debug.log('ALERT:', alertString);}; 

var confirmValue = true; //set this before you expect the confirm statement to be shown 
confirm = function (confirmString) { 
    debug.log('CONFIRM:', confirmString, confirmValue); 
    return confirmValue; 
}; 

確認那我只能說:

describe("test", function() { 
    it('should test true confirm workflow', function() { 
     confirmValue = true; // or false if you like 
     //expect outcomes that would come from any confirms being called with true 
    }); 
}); 

這不完美,我如果您有多次確認可以在設置confirmValue之間彈出,您可能會遇到麻煩。也許那麼設置一個預期確認返回值的提示會很好......棘手......

+0

迄今爲止3個答案中的IMO,這個解決了尼克問的問題。今天在Stackoverflow上,關於Javascript中靜態模擬的內容很少,除了你的答案。 –