Spy和callThrough原生WebSocket构造函数和Jasmine
我试图监视本机Spy和callThrough原生WebSocket构造函数和Jasmine,websocket,jasmine,Websocket,Jasmine,我试图监视本机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("
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
这样的构造函数?我找到了callFake
的解决方法:
它工作得很好,但它会覆盖WebSocket.prototype
,因此在创建spy之前,请确保使用它或保存引用,如
当你说“它覆盖了
WebSocket.prototype
所以在创建间谍之前一定要使用id”时,你是什么意思?我在你后来发布的示例中没有看到任何id的引用?谢谢~id~这是一个打字错误。现在好点了吗?啊,是的,我现在明白了,对不起,如果它看起来吹毛求疵,我真的很困惑。谢谢
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();
});
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);
});