2015-05-03 143 views
1

我試圖用sinon.js與此代碼(requirebin)上的WebSocket建設窺探窺探:興農上的WebSocket

sinon = require('sinon'); 

sinon.spy(window, 'WebSocket'); 
// throws an error (see console) 
new window.WebSocket("ws://example.com"); 

在Chrome中失敗與Uncaught TypeError: Failed to construct 'WebSocket': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

在Safari或者不與PhantomJs TypeError: Attempted to wrap object property WebSocket as function

我在做什麼錯?

回答

1

我從興農合作者在GitHub上一個答案:https://github.com/cjohansen/Sinon.JS/issues/743

TL; DR:原生對象是不可靠的間諜/磕碰目標。將它們包裹在你自己的薄包裝紙上,然後間諜/存根:

// totally making things up here 
function WrapWebSocket(){ 
    return window.WebSocket; 
} 

// in your code 
function init(){ 
    var WS = WrapWebSocket(); 
    var ws = new WS(); 
} 

// in your test 
var spy = sinon.spy(); 
sinon.stub(window, 'WrapWebSocket', function(){ 
    return spy; 
}); 
init(); 
assert(spy.calledWith('someurl');