间谍和callThrough与Jasmine的本机WebSocket构造函数 [英] Spy and callThrough native WebSocket constructor with Jasmine

查看:140
本文介绍了间谍和callThrough与Jasmine的本机WebSocket构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试窥探原生的 WebSocket 构造函数,所以我写道:

I'm trying to spy on native WebSocket constructor, so I wrote:

it("should spy and call through WebSocket constructor", function (done) {
  var WSspy = spyOn(window, "WebSocket").and.callThrough();

  var ws = new WebSocket("ws://some/where");

  expect(WSspy).to.toHaveBeenCalledWith("ws://some/where");
});

但会导致错误:

TypeError: Failed to construct 'WebSocket': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

我应该怎样 callThrough 这样的构造函数?

How should I callThrough such constructor?

推荐答案

我找到了一个解决方法 callFake

I found a workaround with callFake:

it("should spy and callFake WebSocket constructor", function (done) {
  var realWS = WebSocket;  
  var WSSpy = spyOn(window, "WebSocket").and.callFake(function(url,protocols){
    return new realWS(url,protocols);
  });        

  var ws = new WebSocket("ws://some/where");

  expect(WSSpy).toHaveBeenCalledWith("ws://some/where");
  done();
});

它工作得很好,但它会覆盖 WebSocket.prototype 因此请确保在创建间谍之前使用它或保存参考,例如

It works quite fine, but it overwrites the WebSocket.prototype so make sure you use it or save the reference before creating the spy, like

var realWS = WebSocket;  
var messageSpy = spyOn(WebSocket.prototype, "close").and.callThrough();      
var WSSpy = spyOn(window, "WebSocket").and.callFake(function(url,protocols){
  return new realWS(url,protocols);
});    

这篇关于间谍和callThrough与Jasmine的本机WebSocket构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆