我正在试图窥探原生的WebSocket
构造函数,所以我写道:
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
这样的构造函数?
答案 0 :(得分:2)
我找到了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
,所以请确保在创建间谍之前使用它或保存引用,如
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);
});