[英]Unit testing of websocket application by sinon.js
I have tried to do unit testing for a web socket application using sinon.js, 我试图使用sinon.js对Web套接字应用程序进行单元测试,
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. 在sinon的 github上的一个用户做了这个,但我无法理解它如何帮助单元测试websocket应用程序来验证发送到假服务器的接收数据。
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()
)? 如何使用假套接字对象的send
方法将数据发送到假服务器(例如: - socket.send()
)? dummySocket.onmessage = function (msg){}
如何在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()
使用sinon.js ,我无法通过分别使用useFakeXMLHttpRequest()
和fakeServer.create()
来创建伪造的websocket对象,如假的XMLHttpRequest
和server
。
Is there any process to achieve this on sinon.js? 在sinon.js上有没有实现这个的过程?
Normally, you would do ws = sinon.createStubInstance(WebSocket)
, but this isn't possible since properties on the WebSocket.prototype throw exceptions when reading them. 通常,您可以执行ws = sinon.createStubInstance(WebSocket)
,但这是不可能的,因为WebSocket.prototype上的属性在读取它们时会抛出异常。 There are two ways around this. 有两种方法可以解决这个问题。
useFakeWebSocket
to sinon to overwrite WebSocket
. 你可以在useFakeWebSocket
添加一个useFakeWebSocket来覆盖WebSocket
。 This would be similar to what useFakeXMLHttpRequest
does to XMLHttpRequest. 这与useFakeXMLHttpRequest
对XMLHttpRequest的作用类似。 Duck type out a WebSocket
object by iterating over the prototype. Duck通过迭代原型来输出WebSocket
对象。
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: 如果你想实现一个模拟echo WebSocket服务器,以便你可以测试你的事件处理程序,你可以这样做:
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. 我希望这就是你要找的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.