【问题标题】:Sinon spy on WebSocketSinon 窥探 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

我做错了什么?

【问题讨论】:

    标签: javascript testing browser websocket sinon


    【解决方案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');
    

    【讨论】:

      猜你喜欢
      • 2018-10-26
      • 2016-10-08
      • 1970-01-01
      • 2016-09-13
      • 2015-06-14
      • 1970-01-01
      • 2017-02-27
      • 2021-01-09
      • 1970-01-01
      相关资源
      最近更新 更多