我正在尝试使用带有此代码(requirebin)的sinon.js来监视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
我做错了什么?
答案 0 :(得分:1)
我从github上的一个sinon合作者那里得到了答案: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');