2015-05-03 93 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');