Sinon 窥探 WebSocket

Posted

技术标签:

【中文标题】Sinon 窥探 WebSocket【英文标题】:Sinon spy on WebSocket 【发布时间】:2015-05-03 22:15:27 【问题描述】:

我正在尝试使用带有此代码 (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

我做错了什么?

【问题讨论】:

【参考方案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');

【讨论】:

以上是关于Sinon 窥探 WebSocket的主要内容,如果未能解决你的问题,请参考以下文章