Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Spy on WebSocket construction does not work #743

Closed
artemave opened this issue May 4, 2015 · 2 comments
Closed

Spy on WebSocket construction does not work #743

artemave opened this issue May 4, 2015 · 2 comments
Labels

Comments

@artemave
Copy link

artemave commented May 4, 2015

Reposting this SO question:

I am trying to spy on WebSocket construction with the following code (requirebin):

sinon = require('sinon');

sinon.spy(window, 'WebSocket');
// throws an error (see console)
new window.WebSocket("ws://example.com");

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

In Safari and PhantomJs it fails with TypeError: Attempted to wrap object property WebSocket as function

What am I doing wrong?

@mroderick
Copy link
Member

Native objects are notoriously unreliable as spying/stubbing targets.

If you're working with a level of indirection like Socket.IO, then I'd recommend targeting that for spying/stubbing. There are examples of how to do this with Sinon.JS.

If you're working closer to the metal, then I'd recommend using a very thin wrapper around the target natives, to allow spying/stubbing.

I created wrapple for this purpose, but it's simple enough to create your own.

// 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');

@artemave
Copy link
Author

artemave commented May 4, 2015

Thanks for the explanation, now I understand what the problem is.

Wrapple seems like a reasonable workaraound. Thanks again!

@artemave artemave closed this as completed May 4, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants