I have tried to do unit testing for a web socket application using sinon.js,
One of the users on github of sinon, did this, but I am not able to understand how it does help to unit test websocket applications for validating the received data which was sent to fake server.
var dummySocket = { send : sinon.spy()};
sinon.stub(window, 'WebSocket').returns(dummySocket);
dummySocket = new WebSocket('ws://html5rocks.websocket.org/echo');
dummySocket.onopen();
dummySocket.onmessage(JSON.stringify({ hello : 'from server' }));
// You can assert whether your code sent something to the server like this:
sinon.assert.calledWith(dummySocket.send, '{"the client":"says hi"}');
My questions are
send
method of fake socket object(eg:- socket.send()
)?dummySocket.onmessage = function (msg){}
With sinon.js, I could not get the any process to create fake websocket object like for fake XMLHttpRequest
and server
by using respectively useFakeXMLHttpRequest()
and fakeServer.create()
Is there any process to achieve this on sinon.js?
You can use a load-testing tool for that. I have used WebLOAD in a similar project. It records the web traffic when using the browser - it records regular HTTP requests and also the web-sockets traffic - you can then play the script back with many users and measure the server's behavior.
It seems that Websocket doesn't provide anything to link client data (request) to server data (response).
Normally, you would do ws = sinon.createStubInstance(WebSocket)
, but this isn't possible since properties on the WebSocket.prototype throw exceptions when reading them. There are two ways around this.
useFakeWebSocket
to sinon to overwrite WebSocket
. This would be similar to what useFakeXMLHttpRequest
does to XMLHttpRequest.Duck type out a WebSocket
object by iterating over the prototype.
beforeEach(function () {
var ws = {};
for (var prop in WebSocket.prototype) {
ws[prop] = function () {}; // some properties aren't functions.
}
});
If you wanted to implement a mock echo WebSocket server so that you can test your event handlers, you could do that with this:
var ws;
beforeEach(function () {
ws = {
send: function (msg) {
this.onmessage({ data: msg });
},
onmessage: function (e) {
// stub
}
};
});
it('should echo', function () {
var spy = sinon.spy(ws, 'onmessage');
ws.send('this is a test');
assertEquals(spy.args[0][0].data, 'this is a test');
});
I hope this is what you're looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With